Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve button by findViewWithTag not working?

Tags:

java

android

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.

like image 509
Mavix Avatar asked Feb 03 '23 09:02

Mavix


2 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.

like image 187
Natali Avatar answered Feb 12 '23 08:02

Natali


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

like image 39
Nikola Despotoski Avatar answered Feb 12 '23 07:02

Nikola Despotoski