Android使用XML相關技巧解析
大家可能還記得,我們在上一篇文章中向大家詳細介紹了Android ListView的相關應用,它主要就是針對于可視化編程。在這里我們會通過Android使用XML來為大家詳細介紹另一種可視化編程方法。
就如跨平臺UI界面庫一樣,Android也是使用XML文件來存貯界元素持布局,現(xiàn)在流行的一些界面組件都是采用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開發(fā)環(huán)境編譯生成的,是映射到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的相關方法就為大家介紹到這里。
【編輯推薦】