Android - how to find multiple views with common attribute

后端 未结 8 1910
野趣味
野趣味 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:48

    This method provides a general way of obtaining views that match a given criteria. To use simply implement a ViewMatcher interface

    private static List getMatchingViews(ViewGroup root, ViewMatcher viewMatcher){
        List 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(getMatchingViews((ViewGroup) child, viewMatcher));
            }
    
            if(viewMatcher.matches(child)){
                views.add(child);
            }
        }
        return views;
    }
    
    public interface ViewMatcher{
        public boolean matches(View v);
    }
    
    // Example1: matches views with the given tag
    public class TagMatcher implements ViewMatcher {
    
        private String tag;
    
        public TagMatcher(String tag){
            this.tag = tag;
        }
    
        public boolean matches(View v){
            String tag = v.getTag();
            return this.tag.equals(tag);
        }
    
    }
    
    
    // Example2: matches views that have visibility GONE
    public class GoneMatcher implements ViewMatcher {
    
        public boolean matches(View v){
            v.getVisibility() == View.GONE  
        }
    
    }
    

提交回复
热议问题