Android學習筆記(五):Activity和main.xml檔案

來源:互聯網
上載者:User

我們在Andriod學習筆記(三):Andriod程式架構,中對main.xml檔案進行了初步的瞭解,這本次,我們將初步學習Activity和main.xml的關係。

雖然我們可以使用java code來編寫UI,但是更通用的方式是使用XML-based Layout檔案,它用於描述widget和container之間的關係。這使得我們可以方便閱讀和是UI設計獨立,也使得一些IDE工具可以提供直觀的GUI。

1、修訂main.xml

<!-- 線性布局,從上到下,方向由orientation的方向確定 fill_parent即填充其父控制項,這裡就是全屏。-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <!-- 如果在Java source code中對此widget有由代碼,需提供id,andriod:id="@+id/<name>",在R.java上有對應的代碼,對應為R.id.<name>, 在這個例子中我們在R.java中查到:R.id.myTextView=0x7f040000,我們可以通過name,在程式中對應這個空間。-->
  <TextView 
      android:id="@+id/myTextView"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />
  <!-- 增加一個新的控制項button,Button:是widget的名字,如果我們定義我們自己的widget(是andriod.view.View的子類),我們需要給出完整的包路徑,例如com.wei.andriod.MyWidget)。-->
  <Button 
      android:id="@+id/myButton"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />
</LinearLayout>

2、在原始碼中,通過我們在xml中定義的名字來擷取該執行個體

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //R.layout.main,就是在R.java中的R類定義的layout中main,格式為:R.layout.<layout的xml檔案名稱字>,就是對應的res/layout/main.xml檔案。
        setContentView(R.layout.main);
        TextView myTextView = (TextView) findViewById(R.id.myTextView);
        myTextView.setText("我的Activity");
        Button myButton = (Button) findViewById(R.id.myButton);
        myButton.setText("我的按鈕");
    }

3、運行,。

相關連結:
我的Android開發相關文章

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.