Enumerate/Iterate all Views in Activity?

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

If you have all your Views in a LinearLayout or an other container that extends ViewGroup you can use the functions getChildCount() and getChildAt(int) and iterate through all of the
contained views.

Hope this helps.


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;

    }