Android layout_weight详解

在学习layout_weight属性的时候在网上找了几篇文章说的我都不怎么理解,最后通过自己写的Demo 测试总结了一下,具体看下面的规则。

场景1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:orientation="horizontal"
   >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:text="Button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Button2" />

</LinearLayout>



注意这里Button的layout_width设置为代码权重设置为2:1
我们看到的结果却是1:2

 

场景2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:orientation="horizontal"
   >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:text="Button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Button2" />

</LinearLayout>


这里Button的layout_width设置为wrap_content 代码权重设置为2:1
结果是 2:1这才是我们要的结果


下面我们要分析一下上面场景1和场景2

规则:

LinarLayout中layout_weight属性
首先按照控件声明的尺寸进行分配然后再将剩下的尺寸按照weight分配
假设屏幕的宽为L
情况1:android:layout_width="wrap_content"
计算过程:
第一次计算
button1   宽为0   button2   宽为0 
第二次计算: 剩下空间宽为:L
button1   宽为L/3   button2   宽为L*2/3 
那么最后的结果:
button1   宽为L/3   button2   宽为L*2/3   也就是我们看到1:2


情况2:android:layout_width="fill_parent|match_parent"
计算过程:
第一次计算
button1   宽为L   button2   宽为L 
第二次计算: 剩下空间宽为: -L
button1   宽为-L/3   button2   宽为-L*2/3 
那么最后的结果:

button1   宽为L*2/3   button2   宽为L/3   也就是我们看到2:1


欢迎大家吐糟!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值