6

Given a new screen in android i would like to iterate through all the viewgroups and views in order to discover all buttons,text fields, spinner etc... is this possible ?

Mike G
  • 4,829
  • 11
  • 47
  • 76

3 Answers3

7

I get the view count and then use that as a counter to call getChildAt(int index)

Mike G
  • 4,829
  • 11
  • 47
  • 76
4

This question may have been long answered, but I wrote this recursive function to set onClickListeners for any buttons I find in my layout, but it could be repurposed:

private void recurseViews(ViewGroup v) {
    View a;
    boolean isgrp = false;
    for(int i = 0; i < v.getChildCount(); i++) { //attach listener to all buttons
        a = v.getChildAt(i);
        if(a instanceof ViewGroup) setcl((ViewGroup) a);
        else if(a != null) {
            //do stuff with View a
        }
    }
    return;
}

EDIT: Casting a View as ViewGroup does not raise an exception as had I previously thought, so the code is much shorter now

A Person
  • 1,350
  • 12
  • 23
0

You could use this to get all child views inside a parent layout, returns an array list of views.

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

if you want to get a specific view you can use this example. It takes all TextView inside a layout.

public List<TextView> getAllTextViews(ViewGroup layout){
        List<TextView> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof TextView){
                views.add((TextView)v);
            }
        }
        return views;
    }

As long as the object you're trying to get derives from View class, it will work.

NJY404
  • 349
  • 3
  • 14