Android 制作布局问题:android:layout_weight 属性不生效
android:layout_weight="1"
- 在 Android 开发中,在 XML 布局文件中,
android:layout_weight属性不生效
问题原因
android:layout_weight属性只在LinearLayout布局中生效即,
android:layout_weight属性只在 LinearLayout 及其子类中有效确保父容器是
LinearLayout,而不是RelativeLayout、ConstraintLayout等对于水平 LinearLayout,子视图的
android:layout_width应设为0dp,对于垂直 LinearLayout,子视图的android:layout_height应设为0dp
处理策略
- 确保父容器是
LinearLayout,而不是RelativeLayout、ConstraintLayout等
<!-- RelativeLayout 中 android:layout_weight 属性不生效 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView 1" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView 2" />
</RelativeLayout>
- 对于水平 LinearLayout,子视图的
android:layout_width应设为0dp
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView 1" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView 2" />
</LinearLayout>
- 对于垂直 LinearLayout,子视图的
android:layout_height应设为0dp
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="TextView 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="TextView 2" />
</LinearLayout>

浙公网安备 33010602011771号