Neil Neil - 22 days ago 11
Android Question

Android: How to find views by type

Ok so I have a layout xml similar to the following example:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/tile_bg" >

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="10dp" >

<LinearLayout
android:id="@+id/layout_0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<!-- view stuff here -->
</LinearLayout>

<!-- more linear layouts as siblings to this one -->

</LinearLayout>




I actually have about 7 LinearLayout items each with id increasing from layout_0 etc. I want to be able to get hold of all the LinearLayout items under the root LinearLayout. Do I need to put an id on the root one and find all others by id or can I get them by type.

The code I use to inflate the layout is:

View view = (View) inflater.inflate(R.layout.flight_details, container, false);


I read somewhere that you can iterate children of a ViewGroup but this is only a View.

What is the best way to get a bunch of children by type?

Answer

This should get you on the right track.

LinearLayout rootLinearLayout = (LinearLayout) findViewById(R.id.rootLinearLayout);
int count = rootLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
    View v = rootLinearLayout.getChildAt(i);
    if (v instanceof LinearLayout) {
        ...
    }
}
Comments