【发布时间】:2015-08-04 20:27:47
【问题描述】:
如何引用后面的 XML 元素?
这是一个特定的用例。假设我有一个带有根 LinearLayout 的表单,其中包含多行的 LinearLayout,每一行都有一个或多个文本输入区域。
这是我要实现的目标的视觉效果。第一张图片来自 Venmo 的应用程序,第二张是以下 XML 的渲染。
这样的布局可能如下所示:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/row_card_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/card_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nextFocusDown="@id/month"/>
</LinearLayout>
<LinearLayout
android:id="@+id/row_date"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/month"
android:layout_height="wrap_content"
android:layout_width="100dp"
android:nextFocusDown="@id/year"/>
<EditText
android:id="@+id/year"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</LinearLayout>
</LinearLayout>
在这个用例中,前向引用是必要的,以便设置下一个焦点元素。这样,当您按下键盘上的下一个按钮时,它将转到正确的视图。在这个示例 xml 中,如果没有 nextFocusDowns,按下一步会从名称转到月份,而永远不会转到年份。
但是,如果你尝试编译这个,你会得到一个错误:
错误:(18, 36) 未找到与给定名称匹配的资源(在 'nextFocusDown' 处,值为 '@id/month')。
这是因为 ID month 在我尝试引用它时尚未初始化,因为它在文件的后面。如何引用 xml 中稍后出现在文件中的 id?
【问题讨论】:
-
这是一个自我回答的问题。我真的没有找到其他可以很好地解释这一点的东西,所以我想我会自己做。欢迎提出改进建议:)
标签: android xml android-layout android-linearlayout