Android - how to find multiple views with common attribute

后端 未结 8 1923
野趣味
野趣味 2020-12-05 02:28

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

8条回答
  •  心在旅途
    2020-12-05 02:49

    Shlomi Schwartz's method has one flaw, it does not collect Views wchich are ViewGroups. Here is my fix:

    private static ArrayList getViewsByTag(ViewGroup root, String tag){
        ArrayList views = new ArrayList();
        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;
    }
    

提交回复
热议问题