有时候我们在适配屏幕的时候可能需要用到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这个属性有没有更加清楚了呢?