如何在 Android 布局中自动进行 `layout_below` 顺序控制?

How do I automatically `layout_below` sequential controls in an Android layout?

我似乎经常制作 Android 具有一系列控件的布局,这些控件旨在一个位于另一个下方。例如

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/a"/>

    <TextView
        android:id="@+id/b"
        android:layout_below="@+id/a"/>

    <TextView
        android:id="@+id/c"
        android:layout_below="@+id/b"/>

    <TextView
        android:id="@+id/d"
        android:layout_below="@+id/c"/>

    <TextView
        android:id="@+id/e"
        android:layout_below="@+id/d"/>

</RelativeLayout>

android:layout_below 属性是必需的:没有它们,所有 TextView 都聚集在同一个地方。

它们通常也是冗余的,并且是错误和乏味的一般来源。随着控件 ID 的变化,随着控件的添加和删除,所有这些字符串都必须进行编辑以正确匹配。为了说明这个方案的一般冗余,请注意它是如何推广这种意大利面的:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/e"
        android:layout_below="@+id/d"/>

    <TextView
        android:id="@+id/b"
        android:layout_below="@+id/a"/>

    <TextView
        android:id="@+id/d"
        android:layout_below="@+id/c"/>

    <TextView
        android:id="@+id/a"/>

    <TextView
        android:id="@+id/c"
        android:layout_below="@+id/b"/>

</RelativeLayout>

我可以看到明确的 layout_below 指令(以及诸如 layout_above 之类的朋友)在某些情况下是多么有用。但是有没有办法配置布局(例如RelativeLayout)来简单地假设它包含的系列中的每个控件应该自动layout_below前面的控件?

您要查找的是 LinearLayout 垂直方向。

LinearLayout可能更适合这种UI结构。它完全满足您的需求,并且会自动为您完成。您真正需要指定的只是它的 android:orientation ,它可以是 verticalhorizontal.

可以找到有关 LinearLayout 的更多信息 here

All children of a LinearLayout are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row high (the height of the tallest child, plus padding).

这是一个简单的例子:

<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">

  <TextView
    android:id="@+id/text_view_a"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hey, I'm TextView A!"/>

  <TextView
    android:id="@+id/text_view_b"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hey, I'm TextView B!"/>

  <TextView
    android:id="@+id/text_view_c"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hey, I'm TextView C!"/>

  <!-- ..and so on. -->

</LinearLayout>