android - 从布局中获取具有重复 ID 的视图
问题描述
我想显示以下五次
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/message"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/add"/>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/separator_height"
android:background="@color/separator"/>
因此我将它存储在 data_item.xml 并尝试通过调用它
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:id="@+id/data_one"
android:layout_height="match_parent">
<include layout="@layout/data_item"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:id="@+id/data_two"
android:layout_height="match_parent">
<include layout="@layout/data_item"/>
</LinearLayout>
但是,如果我这样做,那么 data_item.xml 布局中的所有项目都将具有重复的 Id。我将如何确保他们没有重复的 id,或者至少以某种方式检索它们?假设我想从 data_three 衬垫布局中获取标题视图文本。我该怎么做?
解决方案
第一个问题是为什么你不使用ListView
而不是在你的适配器中设置值?这个更好。
但是如果你必须以这种方式设计你的布局,你必须首先从你的 LinearLayout 中获取参考,通过使用 LinearLayout 参考找到你的视图,如下所示:
LinearLayout dataOne = findViewById(R.is.data_one);
TextView dataOneTitle = dataOne.findViewById(R.id.title);
推荐阅读
- tkinter - Tkinter 获取窗口或顶层中使用的最后一行
- javascript - 在月视图中返回日历总是回到一个月,
- reactjs - ReactJS、Axios、.NET Core 5.0 WebAPI -- 401 未经授权
- python-3.x - 如果它以问号开头,Python urljoin 不能正确连接字符串
- nuget - Itext7 和 SelectPdf nuget 包
- javascript - 按字符串数组选择类型
- android - Android Studio 在共享测试目录中显示未解析的引用,但执行任务按预期工作
- bash - Bash 运行两个命令都依赖于第一个
- docker - Docker build 在另一个目标下执行指令(多阶段)
- authentication - 错误:无法找到或加载主类 org.apache.zookeeper.server.auth.DigestAuthenticationProvider