首页 > 解决方案 > 从布局中获取具有重复 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 衬垫布局中获取标题视图文本。我该怎么做?

标签: androidandroid-layoutandroid-viewandroid-include

解决方案


第一个问题是为什么你不使用ListView而不是在你的适配器中设置值?这个更好。

但是如果你必须以这种方式设计你的布局,你必须首先从你的 LinearLayout 中获取参考,通过使用 LinearLayout 参考找到你的视图,如下所示:

LinearLayout dataOne = findViewById(R.is.data_one);
TextView dataOneTitle  = dataOne.findViewById(R.id.title);

推荐阅读