如何防止相对布局折叠

How to prevent relative layout from collapsing

您好,我目前正在制作一个使用相对布局定义的设置菜单

可惜东西太小就塌了。有什么办法可以防止这种情况发生吗?解决此问题的最佳做法是什么?最小宽度?包装?

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:background="@drawable/outline"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Show my picture"
        android:textColor="#7E57C2"
        android:textSize="18dp"
        android:textStyle="bold" />

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

试试这个

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:padding="16dp">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@id/switch1"
        android:text="Show my picture"
        android:textColor="#7E57C2"
        android:textSize="18dp"
        android:textStyle="bold" />

</RelativeLayout>

唯一的变化是,开关固定并与父级右对齐,而文本视图设置在开关的左侧。如果display太小,textview会调整,不会和switch重叠。这里的关键是

android:layout_toLeftOf="@id/switch1"