Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find list of View(s) that has a specific Tag (attribute)

I set tag for UI widgets and I want to retrieve a list of View that has a specific tag. Using View.findViewWithTag("test_tag") just return one View not all view that support tag.

Any help appreciated.

like image 916
Behnam Avatar asked Mar 29 '12 07:03

Behnam


1 Answers

You shouldnt expect an array of views from this method, since the method signature itself tells that it will return a single view.

public final View findViewWithTag (Object tag) 

However, what you may do is to get your layout as ViewGroup and then iterate through all the child views to find out your desired view by doing a look-up on their tag. For example:

/**
 * Get all the views which matches the given Tag recursively
 * @param root parent view. for e.g. Layouts
 * @param tag tag to look for
 * @return List of views
 */
public static List<View> findViewWithTagRecursively(ViewGroup root, Object tag){
    List<View> allViews = new ArrayList<View>();

    final int childCount = root.getChildCount();
    for(int i=0; i<childCount; i++){
        final View childView = root.getChildAt(i);

        if(childView instanceof ViewGroup){
          allViews.addAll(findViewWithTagRecursively((ViewGroup)childView, tag));
        }
        else{
            final Object tagView = childView.getTag();
            if(tagView != null && tagView.equals(tag))
                allViews.add(childView);
        }
    }

    return allViews;
}
like image 66
waqaslam Avatar answered Nov 08 '22 21:11

waqaslam