weightSum 和 layout_weight 以及 为什么有时要设置0dp

本文详细解析线性布局中weight属性的定义及其与width设置的关系,解释了为何在使用weight属性时,对于width设为wrap_content的情况,建议将其改为0dp以提高效率。通过具体计算公式,深入探讨了如何合理运用这些属性来优化界面布局。

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

线性布局(水平为例)的weightSum  定义子控件weight的最大值, 如果未指定,则等于 所有子视图的 layout_weight累加和。

子视图的layout_weight  占用父视图的空间比重。


一个线性布局的子视图真正宽度计算:

 子视图自身的宽度    + 自身比重 / 总比重  *  父视图的宽度


为什么在设置了layout_weigth后,开发环境会 针对 width="wrap_content" 会建议改为 0dp呢,  这样不用再计算自身的宽度了,提高了效率。


http://book.51cto.com/art/201404/435840.htm

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="100dp"> <LinearLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textSize="16sp"/> <TextView android:id="@+id/author" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> <TextView android:id="@+id/time" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> <TextView android:id="@+id/need" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> </LinearLayout> <com.google.android.material.button.MaterialButton android:layout_width="60dp" android:layout_height="100dp" android:layout_marginHorizontal="12dp" app:cornerRadius="6dp" android:textSize="20sp" android:text="报名" android:textStyle="bold"/> </LinearLayout> 如何解决Indicates how much of the extra space in the LinearLayout is allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值