Home » Android » java – Retrieve button by findViewWithTag not working?

java – Retrieve button by findViewWithTag not working?

Posted by: admin June 15, 2020 Leave a comment

Questions:

In the onCreate() method of my class I make a grid of buttons, and give them tags to identify them, for example:

button.setTag("one four");

This is working fine. Now I want to make a new temporary button within a method, and I’m using this code:

String s = "one four";
Object o = s;
View view = new View(this);
Button button = (Button)view.findViewWithTag(o); 

But button always comes out as “null”. And I don’t know why.

How to&Answers:

You must call view.addChild(button); before view.findViewWithTag(o);

And you dont need to do this Object o = s;, view.findViewWithTag(s); will do the same.

View view = new View(this); – you create a new instance of View.
Object view does not have any children. You must call findViewWithTag(s) method from layout which contains your Button object.

Answer:

Try not assigning the string to the object variable and set the tag directly to be your string.

Answer:

Mavix, findViewWithTag traverse all child views and works fine in ViewGroup. Try this:

// after button.setTag("one four");

ViewGroup v = (ViewGroup) findViewById(R.id.myFirstLayoutIdInXmlLayoutFile); 
Button b = (Button) v.findViewWithTag("one four");

Answer:

I had the same doubt. In my situation, I have a Main Layout and a Secondary Layout (inside the Main) – the two were RelativeLayout’s – and I want to get the components I had added on the screen.

But I had to use dynamic keys (which could be repeated)and were the unique parameter I could use to Identify the components.

Like Natali, in her response, I use “TAG” in the components and worked for me. See below (using Button as example):

Step 1: Declare a button-type variable. Button btn = new Button(this); // this is Context of my Activity

Step 2: Set any key. String any_key = "keyToGetButton";

Step 3: Set tag (key setted in step 2) to your button. btn.setTag(any_key);

Step 4: Get your button by tag (in other method, for example). Button button = (Button) your_layout_where_is_button.findViewWithTag(any_key);