LinearLayout布局中的weight的理解

在android中LinearLayout是线性布局,在线性布局中有这样一个属性,android:layout_weight。layout_weight代表的是控件所占剩余空间的比例。

什么是剩余空间

剩余空间就是总的空间大小减去控件自身的大小。例如,控件自身的大小是100dp,总的空间的大小是400dp,那么剩余空间的大小就是400-100=300dp

奇怪现象,加深理解什么是剩余空间的大小

<span style="font-size:14px;"></span><pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#FF0000" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="#00FF00" />

</LinearLayout>


 

在Button1中我们设置了layout_weight=1,在Button2我们设置layout_weight=2;显示效果如下:


这是为什么呢,我们明明设置了button1的layout_weight=1,button2的layout_weight=2,显示的button1:button2=2:1

原因:我们button1的layout_layout=match_parent,所以button1控件自身高度所占空间是button1Height=match_parent;button2的layout_height=match_parent,所以button2控件自身所占高度是button2Height=match_parent。

两个button所占自身所占空间大小的总和是totalHeight=button1Height+button2Height=match_parent+match_parent=2*match_parent.

总的空间大小:在这里就是LinearLayout的layou_height的值,total=match_parent

剩余空间:dalta=total-totalHeight=-match_parent

button1的高度是button1Height+dalta*1/3=match_parent+(-match_parent)*1/3=2/3match_parent

button2的高度是button2Height+dalta*2/3=match_parent+(-match_parent)*2/3=1/3match_parent

是不是button1与button2的比例变成你2:1

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值