引言
LinearLayout作为常用的四大布局之一在开发过程中扮演着重要的角色,而weight属性则是线性布局中所特有的。
weight的使用
首先先说明下控件尺寸的计算公式(以宽度为例):
finalWidth=baseWidth+remianWidth*prop---------------(a)
其中:
finalWidth:最终控件的宽度;
baseWidth:xml中android:layout_width的值
prop:该控件所占的比例
关于weight属性的使用,官方的建议是一致使用“0dp”,但在实际开发中或许会看到一些使用“wrap-content”和“march-content”的情况。
线上布局文件代码(其中XXX未明确,留着后面分析):
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="XXX"
android:layout_height="wrap_content"
android:layout_weight="2"/>
<TextView
android:layout_width="XXX"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:layout_width="XXX"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
下面来计算下各个情况下的weight分配。
假设该LinearLayout的宽度为x。
android:layout-width=”0dp”
按照公式(a),容易得到3个TextView的宽度分别为;
wid_tv01=0+(2/5)*x=2x/5;
wid_tv02=0+(1/5)*x=x/5;
wid_tv03=0+(2/5)*x=2x/5;
则对应的宽度分配为2:1:2。
效果图如下:

此时TextView中设置text属性也是不影响的, 因为baseWidth此时已经设置为0dp了。
android:layout-width=”march-content”
首先计算下剩余宽度remianWidth为:
remainWidth=width_01-width_02;-------------------------(b)
其中:
width_01为实际的最大宽度,即x;
width_02为理论的所需宽度,即3x(3个控件,每个控件一个x);
按照公式(b)可以计算现在的remianWidth=-2x。
按照公式(a),容易得到3个TextView的宽度分别为;
wid_tv01=x+(2/5)*(-2x)=x/5;
wid_tv02=x+(1/5)*(-2x)=3x/5;
wid_tv03=x+(2/5)*(-2x)=x/5;
则对应的宽度分配为1:3:1。
效果图如下:
同样的,现在在TextView中设置text也是没影响的。
android:layout-width=”wrap-content”
第一种未设置text属性,即baseWidth=0;情况同 android:layout_width=”0dp”。
第二种设置了text属性,此时的baseWidth则不为0,假设3个TextView的text宽度分别为均为270dp,LinearLayout的宽度x为360。(数据仅仅为了演示整倍数,无实际意义) 、
按照公式(b),计算得
remianWidth=360-3*270=-450;
按照公式(a),容易得到3个TextView的宽度分别为;
wid_tv01=270+(2/5)*(-450)=90;
wid_tv02=270+(1/5)*(-450)=180;
wid_tv03=270+(2/5)*(-450)=90;
则对应的宽度分配为1:2:1。
效果图如下:

小结
其实控件尺寸weight的分配,只要牢记公式(a)即可,只不过有时候在计算剩余宽度时需要留心下。当然最好还是都按照谷歌建议的统一设置为”0dp”最好。
本文详细解析了LinearLayout中weight属性的使用方式,并通过不同场景下的示例,展示了如何利用weight属性进行灵活的布局控制。
8061

被折叠的 条评论
为什么被折叠?



