2017-05-25 188 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 –

相关问题