Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Neil Avatar asked Dec 14 '12 22:12

Neil


People also ask

What is findViewById () method used for?

FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .

What is R in find view by ID?

findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.

What are the views in Android?

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc. ViewGroup is an invisible container of other views (child views) and other ViewGroup.


1 Answers

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) {
        ...
    }
}
like image 117
Rawkode Avatar answered Sep 19 '22 14:09

Rawkode