Android中使用weight属性时LinearLayout尺寸不固定的问题求助
解决LinearLayout权重布局尺寸随内容变化的问题
核心修改点:将所有子LinearLayout的android:layout_height属性从wrap_content改为0dp。
原因说明
当父LinearLayout为垂直方向时,layout_weight的作用是分配父布局的剩余空间。如果子View的layout_height设为wrap_content,系统会优先为子View分配能容纳内部元素的高度,再把剩下的空间按权重比例分配,这就导致内部添加TextView等元素时,子View高度会被内容撑大。
改成0dp后,系统会完全忽略子View的内容需求,直接按照layout_weight的比例分配父布局的总高度,从而让子LinearLayout的尺寸保持固定。
修改后的完整布局代码
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/light_black" android:weightSum="10" tools:context=".userRegisterActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1.5" android:weightSum="10" android:orientation="vertical"> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="7.5" android:orientation="vertical"> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical"> </LinearLayout> </LinearLayout>
内容的提问来源于stack exchange,提问作者tonykrjhc
相关产品推荐
相关产品推荐

