關於layout_weight,我們一般就理解爲佈局權重的意思,Android官方的說明如下:
Formats: float
Indicates how much of the extra space in the LinearLayout is allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.
可賦值類型爲float,
layout_weight的含義是:在線性佈局中,這些控件各自佔據的空白區域的比重。
爲0,表示該控件不會被拉伸以適應佈局;其他值則表示,控件在佈局空白區域中的佔地比例。
結合實際例子來看看:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="@+id/updateList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="Update the list"></Button>
<Button
android:id="@+id/triggerServiceUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="Trigger service"></Button>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="9"></ListView>
</LinearLayout>
上面的佈局整體由一個豎向的LinearLayout填滿畫布,然後再由一個橫向的LinearLayout和一個listView組成它的兩部分,橫向LinearLayout包含兩個按鈕。我們主要看的是listview的擺放。顯然,按鈕的比重需要小,列表的比重需要大。所以,我們通過制定layout_weight一小一大,就可以了,分別爲1和9,當然個人喜好問題了。
至於按鈕和listview的寬和高,我們需要根據實際情況來佈局,一般來說,在下面的佈局中,我們需要將寬度和畫布的寬度設置爲一樣大,不然就不好看了。而高度則是以字體的大小來定的,所以設置爲wrap_content即可。