问题描述
我有一个包含多个 ImageView
的布局,其中一些图像需要具有相同的 onClickListener.我希望我的代码灵活,并且能够获取那些 View
的集合,在运行时迭代并添加侦听器.
I have a layout with multiple ImageView
s, some of those images need to have the same onClickListener.I would like my code to be flexible and to be able to get a collection of those View
s, iterate and add the listeners at run-time.
是否有像 findViewById
这样的方法可以返回 View
的集合而不是一个?
Is there a method like findViewById
that will return a collection of View
s rather than just a single one?
推荐答案
我终于写了这个方法(更新感谢@SuitUp(更正的用户名)):
I've finally wrote this method (Updated thanks to @SuitUp (corrected username)):
private static ArrayList<View> getViewsByTag(ViewGroup root, String tag){
ArrayList<View> views = new ArrayList<View>();
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = root.getChildAt(i);
if (child instanceof ViewGroup) {
views.addAll(getViewsByTag((ViewGroup) child, tag));
}
final Object tagObj = child.getTag();
if (tagObj != null && tagObj.equals(tag)) {
views.add(child);
}
}
return views;
}
它将返回所有具有 android:tag="TAG_NAME"
属性的视图.享受;)
It will return all views that have android:tag="TAG_NAME"
attribute. Enjoy ;)
这篇关于Android - 如何找到具有共同属性的多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!