Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through viewgroup

Tags:

java

android

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 ?

like image 354
Mike G Avatar asked Nov 28 '11 16:11

Mike G


2 Answers

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

like image 134
Mike G Avatar answered Sep 18 '22 01:09

Mike G


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

like image 23
2 revs Avatar answered Sep 20 '22 01:09

2 revs