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

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

问题描述

我有多个布局的ImageView S,其中一些图像都需要有相同的onClickListener。 我想我的code灵活,并能够得到这些集合查看 S,迭代和在运行时添加的侦听器。

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 将返回查看集合取值,而不仅仅是一个单一的呢?

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_NAME属性。享受;)

这篇关于Android的 - 如何找到有共同属性的多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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