Enumerate/Iterate all Views in Activity?

后端 未结 8 546
忘了有多久
忘了有多久 2020-12-09 17:33

Is there a way to iterate through all the views in your Activity? Something like:

Iterator it = getViewIterator();
...

Does this exi

相关标签:
8条回答
  • 2020-12-09 18:05

    Assuming by "all the views in your Activity" you mean every view in the hierarchy, there's no such Iterator or anything in Android that allows you iterate over all views.

    ViewGroups have getChildCount and getChildAt methods, but they are about direct children of the ViewGroup. So, you would need to visit every child, and check if it's a ViewGroup itself, and so on. Long story short, I wanted such a functionality to find all views that match a specific tag (findViewWithTag only returns the first). Here is a class which can iterate all views:

    public class LayoutTraverser {
    
        private final Processor processor;
    
    
        public interface Processor {
            void process(View view);
        }
    
        private LayoutTraverser(Processor processor) {
            this.processor = processor;
        }
    
        public static LayoutTraverser build(Processor processor) {
            return new LayoutTraverser(processor);
        }
    
        public View traverse(ViewGroup root) {
            final int childCount = root.getChildCount();
    
            for (int i = 0; i < childCount; ++i) {
                final View child = root.getChildAt(i);
    
                if (child instanceof ViewGroup) {
                    traverse((ViewGroup) child);
                }
            }
            return null;
        }
    }
    

    Use it like this:

    LayoutTraverser.build(new LayoutTraverser.Processor() {
      @Override
      public void process(View view) {
        // do stuff with the view
      }
    }).traverse(viewGroup);
    
    0 讨论(0)
  • 2020-12-09 18:08

    Here is my example, based on Harry Joy's answer. It iterates through all hierarchies of the parent ViewGroup to see if any of the views anywhere within it are a Button:

    private boolean doesViewGroupContainButton(ViewGroup parentView) {
    
            int numChildViews = parentView.getChildCount();
            for (int i = 0; i < numChildViews; i++) {
                View childView = parentView.getChildAt(i);
                if (childView instanceof ViewGroup) {
                    if (doesViewContainButton((ViewGroup)childView)) {
                        return true;
                    }
                }
                else if (childView instanceof Button) {
                    return true;
                }
            }
            return false;
    
        }
    
    0 讨论(0)
提交回复
热议问题