Ahmad
Ahmad

Reputation: 72533

Android - Different Ids for the same include Layout

I have a layout which I have to Include several times. It consists of a TextView and an ImageView:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:background="@drawable/back2"
    android:id="@+id/id_1"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/id_2"
    android:textSize="15dp"
    android:typeface="sans"
    android:textColor="#ffffff" />

Now I want to set the text programmatically, but the problem that I'm facing is, that the TextView now always has the same Id, because I'm including the same Layout several times. Is there a way to programmatically include a Layout and always change the Id for each included layout?

Upvotes: 5

Views: 1824

Answers (5)

Ratna Halder
Ratna Halder

Reputation: 2004

You can use this to change your TextView id
TextView textview = new TextView(this); textview.setId(int id);

Upvotes: 1

AggelosK
AggelosK

Reputation: 4341

You can create your TextView dynamically and then use TextView.setId(int id) to set the id of that View so that you can call it later with the new id.

Upvotes: 2

IAmGroot
IAmGroot

Reputation: 13855

For each textview

Change the id in the line android:id="@+id/id_2" to a different id.

For example:

android:id="@+id/id_4"

To add them programmatically you can do this:

            TextView Label3 = new TextView(this);
            Label3.setId(300);
            Label3.setTextAppearance(this, android.R.attr.textAppearanceMedium);
            Label3.setLayoutParams(labelParams);
            Label3.setText("My textViewCaption:");
            ll3.addView(Label3);

and if you set Label3 as a global variable, you can access it to change it, via setText

Programmatically you can loop through this and set the Ids while you loop

Upvotes: 1

nEx.Software
nEx.Software

Reputation: 6862

What I'd do is, when you need to access the views on a particular instance of the included layout:

ViewGroup instance = (ViewGroup) findViewById(R.id.included1); // Replace ViewGroup with whatever your particlar type is
ImageView iView = (ImageView) instance.findViewById(R.id.id_1);
TextView tView = (TextView) instance.findViewById(R.id.id_2);

Upvotes: 8

Alex Lockwood
Alex Lockwood

Reputation: 83303

As far as I know there is no way to do this. You'll have to create the layout w/o using <include> if you want the ids in your XML layout to be unique.

Upvotes: 1

Related Questions