Restore findViewWithTag button not working?

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

button.setTag("one four"); 

It works great. Now I want to create a new temporary button in the method, and I use this code:

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

But the button is always displayed as "null". And I do not know why.

+6
source share
4 answers

You should call view.addChild(button); to view.findViewWithTag(o);

And you do not 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 . The View object has no children. You must call the findViewWithTag(s) method from the layout that your Button object contains.

+8
source

Do not try to assign a string to an object variable and set the tag directly in your string.

+1
source

Mavix, findViewWithTag moves all child views and works fine in ViewGroup. Try the following:

 // after button.setTag("one four"); ViewGroup v = (ViewGroup) findViewById(R.id.myFirstLayoutIdInXmlLayoutFile); Button b = (Button) v.findViewWithTag("one four"); 
0
source

I had the same doubts. In my situation, I have a main layout and an additional layout (inside the main one) - two were RelativeLayout - and I want to get the components that I added on the screen.

But I had to use dynamic keys (which could be repeated) and were the only parameter that I could use to identify components.

Like Natali, in her answer , I use β€œTAG” in components and worked for me. See below (using the button as an example):

Step 1: Declare a button type variable. Button btn = new Button(this) ; // this is the context of my activity

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

Step 3: Install the tag (the key installed in step 2) on your button. btn.setTag(any_key);

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

0
source

Source: https://habr.com/ru/post/906946/


All Articles