Android Layout_weight 解密

首先看一个布局:

<?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="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff0000"
        android:text="1"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#cccccc"
        android:text="2"
        android:textColor="#000000" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#ddaacc"
        android:text="3"
        android:textColor="#000000" />

</LinearLayout>

看到这个布局,很容易想到出来的结果是什么样的:
这里写图片描述

然后,再来看一下改动一下的布局:

<?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="horizontal" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff0000"
        android:text="1"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#cccccc"
        android:text="2"
        android:textColor="#000000" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#ff0000"
        android:text="3"
        android:textColor="#000000" />

</LinearLayout>

看到这里,如果你想的还是按照: 1/5 2/5 2/5 来分的话,那就错了。

不多说,直接看结果:
这里写图片描述

这才是真正的结果。

总结计算方法:
1、layout_weight 这个值是,如果不指定,则默认为0,Android系统先按照你设置的控件高度Layout_width值wrap_content,给你分配好他们3个的宽度,然后再会把剩下来的屏幕空间按权重分配给有权重的控件。
2、所以,上面这个例子。这样算才对:
假设屏幕宽度为1,先按照设置的match_parent给它们设置相应的宽度先,则每人都是1,这时候算出剩余的屏幕宽度(这里说明一下,这个值是可以为负值的)为:1-3*1=-2(因为每个都是1,所以三个,就占用了3),剩下的屏幕宽度为-2。然后,把这个剩下的-2按照权重分配给每个空间。例如第一个最后的宽度应该是这样的:1+(1/5)x(-2)=3/5 第二个是:1+(2/5)x(-2)=1/5 第三个是:1+(2/5)x(-2)=1/5
3、所以,理解最重要。看不出来,就动手算一下,不用靠猜了,我也是每次都会忘记,这次应该不会了。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值