Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I to findViewByTag?

Tags:

android

Say I have dynamically generated some amount of LinearLayout, all with different tags.

for (int i = 0; i <= 5; i++)
{
        final LinearLayout LinLayBtn = new LinearLayout(this);
        LinLayBtn.setTag( "id"+String.valueOf(i) );
         ...

And now I need to somehow access this layout by they tag number from a different method.

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("1");

What would be the best way to do that?

Thanks!

like image 284
Roger Avatar asked Sep 17 '11 15:09

Roger


1 Answers

Have you tried it this way and found a problem with it?

You'll need to make this line

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("1");

match the naming scheme you used when you set the tag. So you'd want something like this in your example:

LinearLayout LinLayBtn = (LinearLayout)findViewWithTag("id1");

If you need to do many of these lookups though it would probably be a better approach to store the view references in an array while you are creating them so you don't have to have all of the findView calls. Or do like @Muhammad suggested and use parent.getChild(index i);

like image 191
FoamyGuy Avatar answered Nov 01 '22 23:11

FoamyGuy