Legich
Legich

Reputation: 27

How to use Android view element by tag

I have some TextView elements in my layout file like below:

<Table Layout>
    ...

    <TableRow android:gravity="center_horizontal">    
        <TextView
            android:id="@+id/tv1"
            android:text="@string/text_value"
            android:tag="id1">

     ...

    <TableRow android:gravity="center_horizontal">    
        <TextView
            android:id="@+id/tv1"
            android:text="@string/text_value"
            android:tag="idN">

     ...

</TableLayout>

I want to use

  for (int i=0; i < 10; i++) {
     myText = (TextView) findViewbyTag("id"+i);
     myText.setText("id is - "+i);
  } 

construction to match each tag value and set text value into each TextView element. It doesn't work! I understand how tp use it by id, but id is int value from resources and I can't generate it in my for() construction.

What can I do? How do I use findViewbyTag?

Upvotes: 1

Views: 1466

Answers (1)

sergej shafarenka
sergej shafarenka

Reputation: 20406

You don't need to use tags. You should rather use dynamical resource retrieval as following.

for (int i=0; i < 10; i++) {
  // generate id dynamically
  int id = getResources().getIdentifier("tv"+i, "id", getPackageName());
  // find view by generated id
  TextView myText = (TextView) findViewbyId(id);
  myText.setText("id is - tv"+i);
}

The both getResources() and getPackageName() are the methods of Context.

Upvotes: 2

Related Questions