Behnam Behnam - 10 months ago 62
Android Question

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

just return one View not all view that support tag.

Any help appreciated.

Answer Source

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));
            final Object tagView = childView.getTag();
            if(tagView != null && tagView.equals(tag))

    return allViews;