关于LinearLayout中的weight的属性

     有时候我们在适配屏幕的时候可能需要用到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这个属性有没有更加清楚了呢?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值