Android - how to find multiple views with common attribute

后端 未结 8 1886
野趣味
野趣味 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 03:07

    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;
    }
    

    It will return all views that have android:tag="TAG_NAME" attribute. Enjoy ;)

    0 讨论(0)
  • 2020-12-05 03:11

    There is no such method as findViewById that returns a group of views, but you can iterate over your views and set them an onClickListener like this:

    for (int i = 0;i < layout.getChildCount();i++) {
      View child = layout.getChildAt(i);
      //you can check for view tag or something to see if it satisfies your criteria
      //child.setOnClickListener...
    }
    

    UPD: For recursive view hierarchy (this is example from a real project, where we do view refresh recursively, but instead you could just do whatever you want with the nested views):

    private void recursiveViewRefresh(ViewGroup view) {
        for (int i = 0;i < view.getChildCount();i++) {
            View child = view.getChildAt(i);
            try {
                ViewGroup viewGroup = (ViewGroup) child;
                recursiveViewRefresh(viewGroup);
            } catch (ClassCastException e) {
                //just ignore the exception - it is used as a check
            }
            singleViewRefresh(child);
        }
    }
    
    0 讨论(0)
提交回复
热议问题