在Android XML文件的佈局設計中,我們經常會遇到Android:layout_weight這個屬性。從英文上的意思可以瞭解到,“weight”是指“分量、重要性”,即該屬性指明瞭widget在設計佈局中的重要性。那究竟layout_weight究竟是做什麼用的呢?
在線性佈局中(LinearLayout)中(默認android:orientation="horizontal"),我們可以使用layout_weight爲其視圖(View)包含的小組件(widget)或者是容器(container)指定填充權值(重要度)。既是我們可以允許視圖中的widget按照layout_weight所指定的數值,按比例分配來填充屏幕的空間。如果我們不指定這個屬性,則系統默認爲0 ,此時它表示按照widgets實際大小來顯示;若layout_weight大於0,則表明存放視圖組件的容器空間會按每個組件的layout_weight的值來按比例分配。爲了更好更直觀地說明這個問題,我用之前做計算器的一部分XML代碼來進行舉例說明:<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:background="#F000"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical" >
<EditText
android:id="@+id/etResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:textSize="25sp"
android:text=""
android:layout_gravity="center"
android:gravity="left"
android:cursorVisible="true"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="4dp"
/>
<TableLayout
android:id="@+id/tablelayoyt"
android:layout_marginTop="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="@+id/linearlayout02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/btnC"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="@string/delete"
android:layout_weight="2"/>
<Button
android:id="@+id/btnCE"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="@string/deleteall"
android:layout_weight="1"/>
</LinearLayout>
</TableRow>
</TableLayout>
</LinearLayout>
1、 首先應讓兩個Button的layout_width="fill_parent"
第一個Button的layout_weight設置爲“2”,第二個Button的layout_weight設置爲“1”,運行結果如下:
從圖中我們可以看到,第一個按鈕的長度爲第二個按鈕長度的1/2,既是屏幕長度的1/3,以此類推。這也說明了,如果layout_width="fill_parent"時,layout_weight的值越小,則該widget佔用的空間長度比例越高。
2、 讓兩個Button的layout_width="wrap_content"
第一個Button的layout_weight設置爲“2”,第二個Button的layout_weight設置爲“1”,運行結果如下:從此圖可以看出,它與layout_weight=”fill_parent”完全相反。這說明了,如果layout_weight=”wrap_content”時,layout_weight的值越小,則該widget佔用的空間長度比例越低。
3、 兩個Button的layout_width屬性相等,layout_weight="1"
如下圖所示:從圖中可以看出,兩個Button的長度相同。這說明了,如果設計佈局中的所有widget的layout_weight都相同,則它們會按照同樣的比例來填充屏幕空間。