2017-05-25 23 views
3

我是android新手。在瞭解佈局的「weight」屬性時,我感到困惑。
我知道當layout_width設置爲0dp時,每個元素將佔用weight/weightSum。 但是當layout_width設置爲match_parrent(可能不推薦),但它有點複雜。
有人說,公式爲:
Android佈局權重:如何解釋寬度設置'match_parent'時的比例計算

,δ= 1-numOfElement;
ratio [i] = 1 + delta *(weight [i]/weightSum);

舉個例子,以清楚〜

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal"> 

    <EditText 
     android:id="@+id/edit_message" 
     android:layout_width="match_parent" 
     android:layout_weight="2" 
     android:layout_height="wrap_content" 
     android:hint="@string/edit_message" /> 

    <Button 
     android:text="@string/button_cancel" 
     android:layout_weight="3" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:onClick="sendMessage"/> 
    <Button 
     android:text="@string/button_send" 
     android:layout_weight="4" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"/> 

</LinearLayout> 

有3個元素,因此,δ= 1-3 = -2;
weightSum =(2 + 3 + 4)= 9;
ratio [0] = 1 +( - 2)(2/9)= 5/9;
比例[1] = 1 +( - 2)
(3/9)= 3/9;
比例[2] = 1 +( - 2)*(4/9)= 1/9;

所以它實際上是5:3:1

但我不明白什麼意思,可能有人解釋說〜
或者,如果公式有誤,請改正〜謝謝

+0

我改變了我對你的具體問題的回答@disinuo –

回答

1

如果在LinearLayout中有兩個視圖,第一個layout_weight爲1,第二個視圖的layout_weight爲2且沒有指定weightSum,默認情況下,weightSum的計算結果爲3(權重之和孩子們),第一個視圖需要1/3的空間,而第二個視圖akes 2/3。

但是,如果我們將weightSum指定爲5,那麼第一個將佔用1/5的空間,而第二個將佔用2/5。因此,總共3/5的空間將被佈局佔用,其餘空置。

Calculation to assign any Remaining/Extra space between child. (not the total space) 

space assign to child = (child individual weight)/(sum of weight of every child in Linear Layout) 

如果兒童中的任何一個被給予0重量然後它佔用來渲染和可用空間的其餘部分由上述式的兒童中分佈

反向發生膨脹所需的最小空間在你的情況,因爲: ,因爲你正在使用match_parent作爲layout_width。權重用於分配剩餘的空白空間,並且您的第一個元素具有匹配父項,因此它會嘗試水平佔用最高空間,剩餘的較小空間將分配給其他兩個子項。

同樣對於第二個孩子,它試圖擴展到最大可用空間,爲最後一個孩子留下很小的空間,因此擴展完全與應用的個人權重相反。

換句話說,在這種情況下, match_parent在這種情況下像老闆一樣占主導地位。 這裏沒有具體的計算,而是按順序排列的兒童優先順序可以很清楚地看到。

+0

我想也許你展示的例子是'layout_width = 0dp'的條件?〜我的問題是'layout_wdith =「match_parent」' – disinuo

+0

是的, 0dp @disinuo –

+0

我改變了我對你的具體問題的回答@disinuo –

相關問題