weight和weightSum
Layout Weight
LinearLayout also supports assigning a weight to individual children with the android:layout_weight attribute. This attribute assigns an “importance” value to a view in terms of how much space it should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view. Child views can specify a weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default weight is zero.
大体意思就是,android:layout_weight 这个属性代表了一个“重要性”的值,这个值的大小代表了该控件能在屏幕中占据多大的空间。这个值越大,表明该控件可以在父控件中占据较多的“ 剩余 ”空间。默认的weight是0。
在这里,大家一定要注意“ 剩余 ”两个字!大家往往容易忽略这一点,导致出现了很多问题。举个例子:水平方向布局的父类有三个子类,父类总的宽度是100,子类的宽度分别是10,20,30。 那么 android:layout_weight 这个属性的目的,就是瓜分剩余的 100 - 10 - 20 - 30,也就是剩余的40的使用权。没错! 就是android:layout_weight 这个属性 仅仅决定 哪个子类能瓜分到更多的40的部分!
android:weightSum
Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children.
这个就很好理解了,weightSum定义了weight 总和的最大值。如果 android:weightSum 没有定义,那么默认值就是通过各个子类的 layout_weight 累加得到。
例子:<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="1">
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/hello_world" />
内部的计算原理是:
Button的宽度 = Button 的 width + Button的weight * 父布局(LinearLayout)的宽度 / weightSum
上面的例子,也就是 Button的宽度 = 0 + 0.5 * LinearLayout的宽度 / 1 = 0.5 * LinearLayout的宽度
也就是Button的宽度将占屏幕的一半。
注意:
在布局文件中的控件,宽高设置成0、固定值、wrap和fill时使用”weight”属性来调整大小的效果是有区别的
当 宽高为固定值时肯定是不行的;
当 android:layout_width(height)=”match_parent”或者“fill_parent”的时候,如果设置了weight属性,那么根据它的weight值(可以理解为优先级)来占据空间,而且这个值是越小,占的空间越大,按且按且相反的大小比例分。
当 android:layout_width(height)=”wrap_parent”的时候,如果设置了weight属性,那么weight值变大占据空间就变大,但是不是按照比例变化,而且weight值达到一定程度控件占据的控件大小就不会在变化。
谷歌工程师推荐大家使用android:layout_width(height)=”0dp”,因为如果你去尝试看就会发现,只有宽或高设置成“0dp”时才是真正的按照“weight”的值按比例设置控件的大小。
关于weight
在相对布局中的控件是不能使用“weight”属性的,但是,在RelativeLayout标签中是可以有“weight”属性的,也就是说你可以用”weight”属性来控制这个相对布局在整个布局中的大小,却不能用”weight”属性来控制这个相对布局中控件的大小。
本文详细介绍了Android中LinearLayout的weight和weightSum属性,weight用于分配控件在屏幕中占据的剩余空间,而weightSum定义了weight总和的最大值。通过实例解析了如何动态设置权重,实现自适应布局。强调了使用'0dp'作为width/height与weight配合使用的重要性,并指出在相对布局中不能直接应用weight属性。
196

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



