Getting child elements from LinearLayout

LinearLayout layout = (LinearLayout)findViewById([whatever]);
for(int i=0;i<layout.getChildCount();i++)
    {
        Button b =  (Button)layout.getChildAt(i)
    }

If they are all buttons, otherwise cast to view and check for class

View v =  (View)layout.getChildAt(i);
if (v instanceof Button) {
     Button b = (Button) v;
}

I would avoid statically grabbing an element from the view's children. It might work now, but makes the code difficult to maintain and susceptible to breaking on future releases. As stated above the proper way to do that is to set the tag and to get the view by the tag.


You can always do something like this:

LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
    v = layout.getChildAt(i);
    //do something with your child element
}

I think this could help: findViewWithTag()

Set TAG to every View you add to the layout and then get that View by the TAG as you would do using ID