线形布局下的layout_weight(比重)属性

在布局文件中设置layout_weight(比重)属性时,以宽为例,假如 android:layout_width="wrap_content",或者 android:layout_width="0dp",此时,设置的layout_weight属性和数值成正比;假如 android:layout_width="match_parent",此时,设置的layout_weight属性和数值成反比

具体说明:

<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">

    <LinearLayout 
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:background="#00f"
        android:layout_weight="1"
        ></LinearLayout>
    <LinearLayout 
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:background="#0f0"
        android:layout_weight="2"
        ></LinearLayout>
</LinearLayout>

效果是这样的:
pic
android:layout_width="wrap_content"设置为android:layout_width="0dp"效果和上图相同。


但是,假如布局文件是:

<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">
    <LinearLayout 
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="#00f"
        android:layout_weight="1"
        ></LinearLayout>
    <LinearLayout 
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="#0f0"
        android:layout_weight="2"
        ></LinearLayout>
</LinearLayout>

效果是:
weight1
这是为什么呢?下面具体说明:
首先要理解layout_weight属性的定义:按比例分摊剩余父布局。第一种情况下,宽度为 0dp,所以剩余空间就是一个父布局的宽度(下面简称父宽),蓝色占的比重是 1,绿色是 2,它们的宽度就是 1:2,很好理解;说说第二种情况:蓝色宽度是match_parent,也就是 1 个父宽,绿色宽度也是match_parent,也是 1 个父宽,蓝色和绿色加起来是 2 个父宽,那么,剩余父布局就是:1 父宽 - 2 父宽 = -1 父宽,它们俩要按比例分摊这 -1 父宽,蓝色是 -1 * 1/3 = -1/3 父宽,绿色是 -1 * 2/3 = -2/3 父宽,蓝色原来占 1 父宽,所以最终结果是:1 父宽 + (-1/3 父宽) = 2/3 父宽,绿色最终结果是:1 父宽 + (-2/3 父宽) = 1/3 父宽,2/3 :1/3 = 2:1,也就是第二幅图的效果了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值