布局XML檔案使用:
就如跨平台UI介面庫一樣,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對應的值。
上述例子是一個簡單的例子,知道了如何載入布局那如何產生,配置這樣的layout檔案呢?
可視化編程:
建立一個項目,步聚就如Hello,World例子中一樣,
然後找到左邊的res/layout/main.xml雙擊開啟,Eclipse右邊會 自動開啟這個xml檔案的layout視圖,視圖周圍有一些操作這個layout的工具列,拖拉一些你想要的
控制項到這個視圖上,那麼xml檔案就會被改變,在最右邊的 Outline視圖中,有這個布局檔案中介面元素的樹狀結構圖。
玩這個東東,想必都會玩,與可視化的VS,Delphi,Swing,QT,沒有任何區別,那我們再來一個小例子吧: