CROSP
CROSP

Reputation: 4617

How to iterate through all activity components(views) in Android

I need to get an array of all activity components, then I need to iterate through this array and choose, for instance, only buttons. How to do this ?

Upvotes: 3

Views: 4737

Answers (1)

Gopal Gopi
Gopal Gopi

Reputation: 11131

this may help you...

public ArrayList<Button> getButtons() {
    ArrayList<Button> buttons = new ArrayList<Button>();
    ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
    findButtons(viewGroup, buttons);
    return buttons;
}

private static void findButtons(ViewGroup viewGroup,ArrayList<Button> buttons) {
    for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
        View child = viewGroup.getChildAt(i);
        if (child instanceof ViewGroup) {
            findButtons((ViewGroup) child, buttons);
        } else if (child instanceof Button) {
            buttons.add((Button) child);
        }
    }
}

Upvotes: 9

Related Questions