關於LinearLayout中的weight的屬性

     有時候我們在適配屏幕的時候可能需要用到weight這個屬性。
     The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views.這段話是android開發文檔中的一句話,意思就是把控件分配完後剩下的空間分配給設置了weight屬性的控件。
     當然直接這樣講比較抽象,下面用一個代碼來證明。
   <Button
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="button1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="button2" />


    <Button
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="button3" />

然後我們來看一下佈局結果
這裏寫圖片描述

我們會很奇怪,爲什麼button2已經設置了layout_width = 0dp,但是卻仍然顯示了寬度,並且已經佔據了剩餘的空間,因此也驗證了上面那段英文的文檔的意思。

再來一個加深印象。
 <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="button1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="button2" />


    <Button
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="button3" />

佈局結果
這裏寫圖片描述

這裏我們先給每一個控件分配寬度,一共是250dp,然後將整個屏幕剩下的空間按照比例分配下去,button1 = 200+(1/3)(match_parent-250)
button2 = 0+(2/3)(match_parent_250) 
button3 = 50
因此,就如我們圖中所示的這樣的結果。
但是當我們設置爲layout_width = match_parent的時候,我們又會發現一個不可思議的結果,比如我們設置權值爲1:2:1的時候,
 <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="button1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="button2" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="button3" />
我們先來看一下這個佈局結果:

這裏寫圖片描述

暈了暈了,在我們的印象中,不是權值大的所佔空間會大嗎?其實並不是這樣的,我們已經解釋過weight的定義,就是這個分配的是控件剩餘的空間,這裏我們設置width = match_parent,所以我們首先給控件分配width值,因爲全部都是match_parent,所以三個button分配了3個屏幕的寬度,所以剩餘的空間大小爲-2屏幕的寬度,然後對應於權值的比例,比如button1 = match_parent+((1/5)*(-2match_parent)) = 3/5match_parent
button2 = match_parent+((2/5)*(-2match_parent))=1/5;
button3 = match_parent+((2/5)*(-2match_parent))=1/5;
所以最後的比例爲3:1:1;
不知道這樣解釋大家對weight這個屬性有沒有更加清楚了呢?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章