android:layout_weight属性的工作原理

本文通过两个具体实例详细解析了Android中LinearLayout布局下layout_weight属性的工作原理。首先介绍了如何根据layout_width和layout_weight属性来分配空间,然后阐述了当Button组件的layout_width设置为0dp时,layout_weight是如何决定组件最终大小的。

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

情形一

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/crime_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="好好学习,天天向上"
            android:layout_weight="1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="click"
            android:layout_weight="1" />
    </LinearLayout>

图1

情形二

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/crime_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="好好学习,天天向上"
            android:layout_weight="1" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="click"
            android:layout_weight="1" />
    </LinearLayout>

图2

比较上面代码运行的结果,我们可以总结android:layout_weight属性的工作原理如下:

第一步,LinearLayout查看layout_width属性值(竖直方位查看layout_height属性)。情形一中两个Button组件的layout_width属性都设置为wrap_content,因此他们获得的空间大小仅够绘制自身。

第二步,LinearLayout依据layout_weight属性值进行额外的空间分配。情形一中,两个Button组件拥有相同的layout_weight属性值,因此他们均分了同样大小的额外空间。若第一个Button组件的layout_weight值设置为2,那么它将获得2/3的额外空间,而第二个Button组件将获得1/3的额外空间。情形二中两个Button组件的layout_width属性都设置为0dp,就避开了第一步,又两个Button组件拥有相同的layout_weight属性值,所以Button组件具有相同的宽度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值