Getting a View with a duplicate id from a layout

585 Views Asked by At

I would like to display the following five times

<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"/>

Thus I store it in data_item.xml and try calling it via

<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>

However if I do that, then all of the items inside data_item.xml layout are going to have duplicate Ids. How would I go about making sure that they do not have duplicate ids, or at least somehow retrieving them? Let's say I want to get title view text from data_three liner layout. How would I do that?

1

There are 1 best solutions below

0
On BEST ANSWER

the first question is why you don't use ListView instead and set values in your adapter? this is better.

But if you have to design your layout in this way, you have to at first get reference from your LinearLayout, the find your view by using LinearLayout reference, as following:

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