Android - 如何找到具有共同属性的多个视图 [英] Android - how to find multiple views with common attribute

查看:17
本文介绍了Android - 如何找到具有共同属性的多个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个 ImageView 的布局,其中一些图像需要具有相同的 onClickListener.我希望我的代码灵活,并且能够获取那些 View 的集合,在运行时迭代并添加侦听器.

I have a layout with multiple ImageViews, 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 Views, iterate and add the listeners at run-time.

是否有像 findViewById 这样的方法可以返回 View 的集合而不是一个?

Is there a method like findViewById that will return a collection of Views 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 - 如何找到具有共同属性的多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆