Android findViewWithTag for multi-tag views

I used the tag to represent using view.setTag(t1);, and then returned the view using parent.findViewWithTag(t1);that returned correctly.

Now I need to set 2 different tags for my views, and I do it with

view.setTag(R.id.tag1, t1);
view.setTag(R.id.tag2, t2);

If tag1 and tag2 are identifiers declared in res / values ​​/ids.xml

Then I try to get the view with the t1 tag, but parent.findViewWithTag(t1);returns null. I searched and there is no method findViewWithTagor the like that will also accept the tag key.

Is there any way to achieve this? If you can’t tell me where this is indicated in the Android documentation,

In this particular case, I could use idinstead of one of the tags, but for situations where this is not possible, I would like to know if this can be done using tags.

+4
source share
3 answers

findViewWithTag(tag)returns the view with the default tag set setTag(tag), compared to tag.equals(getTag()).

+3
source

as a complement to Diegos answer I would like to point out the source code:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/View.java#18288

if (tag != null && tag.equals(mTag)) {

the tag used for comparison and search is one mTagthat is set using the direct method setTag(Object), as can be seen from the source code in this line:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/view/View.java#18505

public void setTag(final Object tag) {
    mTag = tag;
}
+1

Methods View.getTag()or View.findViewWithTag()return only those Objectassigned View.setTag()to a specific View, see also the documentation.

However, you can write your own method findViewWithTag():

public View findViewWithTag(@NonNull View parent, int tagID, @NonNull Object myTag) 
{
    for (int i = 0; i < parent.getChildCount(); i++)
    {
        View v = parent.getChildAt(i);
        if ( myTag.equals(v.getTag(tagID)) )
        {
            return v;
        }
    }
    return null;
}

You can also narrow your search to specific subclasses Viewby adding some condition similar (v instanceof mySpecificView)to the sentence if.

0
source

All Articles