LinearLayout权重的算法

本文通过实例对比,详细解析了在Android LinearLayout布局中,不同宽度设置下(0dp与match_parent)子控件如何根据权重分配剩余空间。展示了具体的计算方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前我们写LinearLayout的控件的权重的时候(以水平方向来说),都会将子控件的的宽度改成0dp
,然后 android:layout_weight=”1”,来表示子控件平分剩余空间。但是,如果子控件的宽度不设置成0dp,那个会是什么情形呢?下面一起来看看他们的区别和算法:

  • 将子控件的宽度设置成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"
    android:gravity="center"
    tools:context="com.example.linearlayout.MainActivity" >

    <Button
        android:layout_width="0dp"
        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"
        />

</LinearLayout>

这里写图片描述

  • 这个很好理解,Button1的宽度为:1/(1 + 2 ) = 1/3。Button2的宽度为:2/(1 + 2 ) = 2/3。但是当把这两个个Button的宽度由0dp改成match_parent的时候,效果还会如上图所示吗?让我们来做个实验,代码如下所示:
<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"
    android:gravity="center"
    tools:context="com.example.linearlayout.MainActivity" >

    <Button
        android:layout_width="martch_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button1"
        />

    <Button
        android:layout_width="martch_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button2"
        />

</LinearLayout>
  • 效果图如下所示:
    这里写图片描述

  • 怎么会和上图不一样呢???这正好是我们要讲的算法,我们都知道,权重的作用是按比例分配屏幕剩余宽度。

  • 算法为:控件自身的宽度 + 按比例分配的屏幕剩余宽度

  • 假设手机屏幕的宽度为W,那么每个Button的宽度也应该都是W,剩余宽度就等于 W - (W + W) = -W。
    Button1的weight=1,剩余宽度占比为1/(1 + 2) = 1/3,所以,最终宽度为 W + (1/3) * (-W) = 2/3W,Button2的计算类似,最终宽度为W + (2/3) * (-W) = 1/3W。所以就能够很好的理解上面两种为什么会有不同的效果了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值