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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With