Android使用layout_weight时子视图无法均分布局空间问题求助
问题原因
水平方向LinearLayout使用layout_weight分配宽度时,如果你给子控件设置的android:layout_width为wrap_content,系统会先计算每个子控件自身内容占据的宽度,再把父容器剩余的空闲宽度按照权重比例分配,最终控件总宽度 = 自身内容宽度 + 分配到的剩余宽度,自然无法实现均等分割。
你的布局里内层LinearLayout包含3个文本控件,自身内容宽度远大于外层第一个单独的TextView,即使权重相同,最终两者占据的总宽度也不一致。
修复方案
- 给参与权重分配的两个子控件(第一个
TextView、内层LinearLayout),将android:layout_width属性从wrap_content修改为0dp,让子控件初始宽度为0,父容器的全部宽度都按照权重比例分配,就能实现严格均分。 - (可选规范优化)给根
LinearLayout显式添加android:orientation="horizontal"属性,LinearLayout默认方向虽为水平,但显式声明可以避免后续修改默认配置、代码动态修改方向时出现非预期的布局问题。
修复后的完整布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <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" tools:context=".MainActivity" android:weightSum="2"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:text="Hello" android:layout_weight="1"/> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:text="Hello"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:text="Hello"/> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:text="Hello"/> </LinearLayout> </LinearLayout>
补充:如果是垂直方向的LinearLayout用权重分配高度,对应要把参与分配的子控件的
android:layout_height设为0dp,原理完全一致。
内容的提问来源于stack exchange,提问作者Vishal Mahavar
相关产品推荐
相关产品推荐

