Android 制作布局问题:android:layout_weight 属性不生效

android:layout_weight="1"
  • 在 Android 开发中,在 XML 布局文件中,android:layout_weight 属性不生效
问题原因
  1. android:layout_weight 属性只在 LinearLayout 布局中生效

  2. 即,android:layout_weight 属性只在 LinearLayout 及其子类中有效

  3. 确保父容器是 LinearLayout,而不是 RelativeLayoutConstraintLayout

  4. 对于水平 LinearLayout,子视图的 android:layout_width 应设为 0dp,对于垂直 LinearLayout,子视图的 android:layout_height 应设为 0dp

处理策略
  1. 确保父容器是 LinearLayout,而不是 RelativeLayoutConstraintLayout
<!-- 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>
  1. 对于水平 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>
  1. 对于垂直 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>
posted @ 2025-09-16 21:02  wzzkaifa  阅读(11)  评论(0)    收藏  举报