Behnam
Behnam

Reputation: 2278

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.

Upvotes: 11

Views: 12480

Answers (3)

Muhammad Ahmad Khan
Muhammad Ahmad Khan

Reputation: 27

Its very simple in my use case. For example there are twelve imageviews with a same tag in a layoyut. When findViewWithTag("image") calls on. It will simply give first index single imageview in from a layout. The solution is simple when you got a imageview with that tag, simply set that imageview tag to empty string. Next time in iteration when findViewWithTag("image") calls on. It will simply give you the next imageview.

for(int inf = 0; inf < albumPageImagesInfoList.get(cardPosition); inf++){
            ImageView imageView = inflateView.findViewWithTag("image");
            if(imageView!=null){
                imageView.setId(uivid);
                imageView.setTag("");
                imgIndexId++;
            }
        }    

Upvotes: 0

user7139867
user7139867

Reputation: 1

 int tags = 6; 
    for (int index = 0; index < tags; index++) {
        try{
            TextView txtView = (TextView)getView().getRootView().findViewWithTag("txtTag-"+index);
            txtView.setText(" TWitter/ @MOIALRESHOUDI ");
        } catch (Exception e){}
    }

hope this helps someone!

Upvotes: 0

waqaslam
waqaslam

Reputation: 68177

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;
}

Upvotes: 18

Related Questions