大家可能還記得,我們在上一篇文章中向大家詳細介紹了Android ListView的相關應用,它主要就是針對於可視化編程。在這裡我們會通過Android使用XML來為大家詳細介紹另一種可視化編程方法。
就如跨平台UI介面庫一樣,Android也是使用XML檔案來存貯界元素持布局,現在流行的一些介面組件都是採用Android使用XML的方式。
在Android中,res/layout資來源目錄下,會有一個或多個.xml檔案,這就是一個介面的布局檔案。我們開啟一個來看看。我開啟當前工程目錄下的res/layout/main.xml檔案。
- < ?xml version="1.0" encoding="utf-8"?>
- < LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- < TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- android:id="@+id/mainview"
- />
- < /LinearLayout>
這個檔案很簡單的布局是指用了一個LinearLayout來布局,裡面只有一個TextView介面元素,也就是一個View.當Activity載入View時,就可以在onCreate中直接載入。this.setContentView(R.layout.main);其中R.layout.main就是一個素引值,是由android開發環境編譯產生的,是映射到res/layout/main.xml的。
所以setContentView(R.layout.main);等價於,按裝main.xml的布局來配置一個layout.然後載入,與如下代碼效果一致
- LinearLayout layout = new LinearLayout(this);
- TextView tv = new TextView(this);
- tv.setText(R.string.hello);
- layout.addView(tv);
- this.setContentView(layout);
其中R.string.hello也是一個資源地圖的ID,是指載入res/values/string.xml中的hello對應的值。
Android使用XML的相關方法就為大家介紹到這裡。