Mavix Mavix - 1 month ago 9
Android Question

Retrieve button by findViewWithTag not working?

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.

Answer Source

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 childs. You must call findViewWithTag(s) method from layout which contains your Button object.