【Android入门的常见问题Part1】android:layout_weight的理解

【本文为本人转载并加注自己的理解融合而成】

最近刚接触android开发,各种教程的第一章都是布局管理,其中的android:layout_weight;属性让我百思不得其解。

经过各种查资料之后终于差不多理解了,希望能帮到其他像我一样的初学者。

layout_weight表示组件的权重,那按我们直观的理解肯定是值越大权重越大啊,其实不然。

Google对权重这个概念的设定有点意思:它表示组件对“剩余”空间的占有比重。怎么来理解呢,举个例子:

[html]  view plain copy
  1. <LinearLayout  
  2.             android:layout_width="match_parent"  
  3.             android:layout_height="wrap_content"  
  4.             android:orientation="vertical" >  
  5.   
  6.             <Button  
  7.                 android:id="@+id/button1"  
  8.                 android:layout_width="match_parent"  
  9.                 android:layout_height="wrap_content"  
  10.                 android:layout_weight="2"  
  11.                 android:text="+"  
  12.                 android:textSize="20sp" />  
  13.             <Button  
  14.                 android:id="@+id/button2"  
  15.                 android:layout_width="match_parent"  
  16.                 android:layout_height="wrap_content"  
  17.                 android:layout_weight="1"  
  18.                 android:text="+"  
  19.                 android:textSize="20sp" />  
  20. </LinearLayout>  

上述布局照我们一般的理解,应该是Button1占2/3的位置,Button2占1/3的位置,但实际上却是反过来的,为什么呢?

因为Google对layout_weight的设定是让组件根据权重来分配剩余的空间。如果一个空间为10,组件1占了3,权重为2,组件2占了2,权重为3,那剩余的5个空间会被两者分割,组件1占:3+(10-5)*2/5=5,组件2占:2+(10-5)*3/5=5,正好分完整个空间。

如果两个组件所占的空间之和超过了整个空间的大小,比如说组件1占了8,权重是2,组件2占了7,权重是3,这样7+8=15超过了10,那该怎么分呢?是这样的,超出的部分也按照权重来分,不过是在组件原来占有空间的基础上来减去这个值。

组件1占:8-(7+8-10)*2/5=6,组件2占:7-(7+8-10)*3/5=4,也是正好分完整个空间。

那我们回过头来看上面代码给出的例子,Button1属性为“match_parent",Button2属性也为"match_parent",意思是两者所占的空间之和为两个空间的大小,超出了整个空间,那按照上面的规则,Button1占:1-(1+1-1)*2/3=1/3个空间大小,Button2占:1-(1+1-1)*1/3=2/3个空间大小。

这就解释了为什么有时候weight值大,占有的权重反而小。

可见,weight值的大小与权重之间并没有直接的关系,每个组件占多大的空间还得具体情况具体分析。那正常的情况下我们还是比较喜欢按weight值来正比例比例分配组件所占的空间大小,该如何操作呢?如下:

[html]  view plain copy
  1. <LinearLayout  
  2.             android:layout_width="match_parent"  
  3.             android:layout_height="wrap_content"  
  4.             android:orientation="vertical" >  
  5.   
  6.             <Button  
  7.                 android:id="@+id/button1"  
  8.                 android:layout_width="0px"  
  9.                 android:layout_height="wrap_content"  
  10.                 android:layout_weight="2"  
  11.                 android:text="+"  
  12.                 android:textSize="20sp" />  
  13.             <Button  
  14.                 android:id="@+id/button2"  
  15.                 android:layout_width="0px"  
  16.                 android:layout_height="wrap_content"  
  17.                 android:layout_weight="1"  
  18.                 android:text="+"  
  19.                 android:textSize="20sp" />  
  20. </LinearLayout>  

只需将android:layout_width属性设置为0px即可,这样,我们声明俩组件都不占空间,

那编译器就会自动分配剩下的空间,Button1:0+1*2/3=2/3,Button2:0+1*1/3=1/3,这样就实现了按weight的值来正比例分配空间。

你可能感兴趣的:(android,Android开发,Google,layout,布局)