gpt4 book ai didi

android - 如何在 Android 布局中自动执行 `layout_below` 顺序控件?

转载 作者:行者123 更新时间:2023-11-29 20:43:41 25 4
gpt4 key购买 nike

我似乎经常制作具有一系列控件的 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 之类的 friend )在某些情况下是多么有用。但是有没有办法配置布局(例如 RelativeLayout)来简单地假设它包含的系列中的每个控件都应该自动 layout_below 前面的控件?

最佳答案

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

可以找到有关 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>

关于android - 如何在 Android 布局中自动执行 `layout_below` 顺序控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com