我为 UI 小部件设置了标签,并且想要检索具有特定标签的视图列表。使用View.findViewWithTag("test_tag")
只返回一个视图,而不是所有支持标签的视图。
任何帮助表示赞赏。
您不应期望从此方法中获得视图数组,因为方法签名本身表明它将返回单个视图。
public final View findViewWithTag (Object tag)
但是,您可以做的是将布局设置为ViewGroup
然后迭代所有子视图,通过查找其标签来找出所需的视图。例如:
/**
* 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)