“LinearLayout ”翻譯成中文是“線性佈局”,所謂線性佈局就是在該標簽下的所有子元素會根據其orientation 屬性的值來決定是按行或者是按列逐個顯示。
示例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/name_text"
/>
< EditText
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" />
< Button
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:text ="@string/cancle_button"
/>
< Button
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:text ="@string/ok_button" />
</LinearLayout >
其對應strings.xml 內容如下:
<?xml version="1.0"encoding = "utf-8" ?>
< resources>
< string name= "hello" > Hello World, UIActivity! </ string >
< string name= "app_name" > 用戶界面</ string >
< string name= "name_text" > 請輸入用戶名</ string >
< string name= "ok_button" > 確定</ string >
< string name= "cancle_button" > 取消</ string >
</ resources>
運行後,如下圖:
“xmlns:android ”指定命名空間,頂級元素必須指定命名空間。而在該命名空間中的控件的屬性如layout_width ,要在屬性前加上“android :”做前綴。
“layout_width ”指定該元素的寬度,可選值有三種,“fill_parent ”、“wrap_content ”、具體數字(單位為px )。其中“fill_parent ”代表填滿其父元素,對於頂級元素來說,其父元素就是整個手機屏幕。“wrap_content ”代表該元素的大小僅包裹其自身內容,而數字則代表其占相應的px 。
“layout_height ”指定該元素的高度,可選參數值與“layout_width ”的參數意義相同。
“orientation ”指定子元素排列方式,其中指定為“vertical ”則是子元素垂直排列,每個子元素會占獨立的一行,如上圖,而另一個可選值為“horizontal ”代表子元素水平排列,即每個子元素會占獨立的一列。示例main.xml 佈局文件如下。其對應的
strings.xml 內容不變。
main .xml
<? xml version = "1.0" encoding ="utf-8" ?>
< LinearLayout
xmlns:android ="http://schemas.android.com/apk/res/android"
android:orientation = "horizontal"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
>
< TextView
android:layout_width = "wrap_content"
android:layout_height = "fill_parent"
android:text = "@string/name_text"
/>
< EditText
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"/>
< Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/cancle_button"
/>
< Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/ok_button" />
</ LinearLayout >
運行後,如下圖:
摘自 瀟灑哥的專欄