Android佈局細節:layout_weight的使用方法

Layout_weight是線性佈局,也就是LinearLayout裏面用到的,下面通過實驗來看這個Layout_weight的特性。

1.當控件的屬性android:layout_width="fill_parent"時,佈局文件如下:

<?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">
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_weight="1"
        android:text="Button1" />
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_weight="2"
        android:text="Button2" />
</LinearLayout>

在這裏Button1的Layout_weight=1,Buttong2的Layout_weight=2,運行效果爲:


我們看到,Button1佔了2/3,Button2佔了1/3。如果此時把button2的weight設置成2000,不是說Button2就消失了,而是Button1的寬度幾乎佔滿了屏幕寬度,而屏幕最後一絲細條則是留給Button2的,已近非常小了,沒有顯示出來。截圖如下:

得出結論:在layout_width設置爲fill_parent的時候,layout_weight代表的是你的控件要優先儘可能的大,但儘可能大是有限度的,即fill_parent.

2.當控件的屬性android:layout_width="wrap_content"時,佈局文件如下:

<?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">
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_weight="1"
        android:text="Button1" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_weight="2"
        android:text="Button2" />
</LinearLayout>
同樣,Button1的weight設置爲1,Button2的weight設置爲2,但是效果與fill_parent的效果截然相反。運行效果如下:

這時,和fill_parent正好相反,Button1的寬度佔據了屏幕寬度的1/3,而Button2的寬度佔據了屏幕的2/3,如果此時把Button2的weight設置爲2000,按照之前理解,Button1應該小的幾乎在屏幕上看不到,但是錯了,實驗告訴我們,當Button1的weight非常小時,也要"wrap_content",也就是要保證Button1至少能夠顯示。以下是Button1設置weight爲2000時的運行截圖:


我們看到,Button1已經足夠小,但是要保證他能顯示出來,因此得出結論:

在layout_width設置爲wrap_content的時候,layout_weight代表的是你的控件要優先儘可能的小,但這個小是有限度的,即wrap_content.

當了解這些後,我們再設計程序時,爲了能夠自適應屏幕,不想給控件一個指定的寬度和高度,就可以使用這個weight屬性來讓它按自己比例來劃分屏幕高度或者寬度了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章