1. 程式人生 > >Android學習筆記(五:Activity和main.xml檔案

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

我們在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、執行,如圖所示。