18

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?

0

9 Answers 9

37

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) {
        ...
    }
}
5
  • 1
    Should be i < count so you don't get an out of range exception.
    – Andres
    Jan 13, 2016 at 17:37
  • Take care that instanceof is a heavy operation. This Aproach can be slow on a view with lots of chlidren Dec 22, 2016 at 13:59
  • 1
    @EmrysMyrooin Expensive calls are only really a problem if they cause delays between inputs. If this is just initialisation within the onCreate method, then it shouldn't matter that much at all since the user hasn't had a chance to do anything anyway. Having said that though, there's no real need for any of this if there are only 7 of them to find. Optimisation would still be needed here. The loop is expensive enough, hanging the UI loop. May 1, 2017 at 3:59
  • When you found needed object in "if (v instanceof LinearLayout) { .. }" block, you can add "break;" clause end of insided block. This is maybe important for performance of this code.
    – The Goat
    Oct 20, 2017 at 11:45
  • It is inconceivable there could be a performance problem with this code
    – Fattie
    Mar 21, 2021 at 14:16
3

You can safely cast your result view to ViewGroup if you know that your layout's root element is any subclass like LinearLayout or other Layouts:

ViewGroup vg = (ViewGroup)view;

and use as you want. If you know that you will always use only one type of layout for root container, you can cast to that type, i.e.:

LinearLayout vg = (LinearLayout)view;
3

Kotlin version of Mir-Ismaili answer:

fun <T : View> ViewGroup.getViewsByType(tClass: Class<T>): List<T> {
  return mutableListOf<T?>().apply {
    for (i in 0 until childCount) {
      val child = getChildAt(i)
      (child as? ViewGroup)?.let {
        addAll(child.getViewsByType(tClass))
      }
      if (tClass.isInstance(child))
        add(tClass.cast(child))
    }
  }.filterNotNull()
}

call it with for example: myViewGroup.getViewsByType(EditText::class.java)

1

You should add an id to the LinearLayout root:

<LinearLayout
    android:id="@+id/root"
    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>

Then inflate the entire layout as usual:

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

Get a hold on your root LinearLayout:

LinearLayout root = (LinearLayout) view.findViewById(R.id.root);

LinearLayout[] children = new LinearLayout[root.getChildCount()];

for (int i = 0; i < root.getChildCount(); i++) {
    children[i] = (LinearLayout) root.getChildAt(i);
}
1

Pass the root view as the argument for this DFS method:

private List<LinearLayout> mArr = new ArrayList<LinearLayout>();

private void getLinearLayouts(ViewGroup parent) {
    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = parent.getChildAt(i);
        if (child instanceof ViewGroup) {
            getLinearLayouts((ViewGroup) child);
            if (child instanceof LinearLayout)
                mArr.add((LinearLayout) child);
        }
    }
}
1

I just wanted to add a more generic one, but you have to keep in mind that it's an heavy approach to do that.

Anyway, here is the code :

private static <T extends View> ArrayList<T> getChildrenOfParentWithClass(ViewGroup parent, Class<T> clazz)
{
    ArrayList<T> children = new ArrayList<>();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++)
    {
        View child = parent.getChildAt(i);
        if (child instanceof ViewGroup)
        {
            children.addAll(getChildrenOfParentWithClass((ViewGroup) child, clazz));
            if (child.getClass().equals(clazz))
            {
                children.add((T) child);
            }
        }
    }

    return children;
}
1
  • You must insert second if block, out of first if block! Aug 20, 2017 at 15:26
1

Simple code in Kotlin. (if the parent is type of ViewGroup such as LinearLayout, FrameLayout... and in your case, LinearLayout is the child type of ViewGroup as well.)

val button= view.children.first { it is Button }

If it is more than one.

val buttons= view.children.filter { it is Button }
0

Like @ChristopheCVB's answer, but supports inheritance also (See tClass.isInstance(child)).

public static <T extends View> ArrayList<T> getViewsByType(ViewGroup root, Class<T> tClass) {
    final ArrayList<T> result = new ArrayList<>();
    int childCount = root.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = root.getChildAt(i);
        if (child instanceof ViewGroup)
            result.addAll(getViewsByType((ViewGroup) child, tClass));

        if (tClass.isInstance(child))
            result.add(tClass.cast(child));
    }
    return result;
}

And a simple example of usage:

ArrayList<TextView> TextViews = getViewsByType(rootLayout, TextView.class);

Thank accepted answer.

0

In my case of Custom Layout all the answers were not working. As these answers are only checking the class existence in child views, but the root view itself can be the class. So using below code solved my issue.

fun <T : View> ViewGroup.getViewsByType(tClass: Class<T>): List<T> {
    fun <T : View> ViewGroup.getSubViewsByType(tClass: Class<T>): List<T> {

        return mutableListOf<T?>().apply {
            for (i in 0 until childCount) {
                val child = getChildAt(i)
                (child as? ViewGroup)?.let {
                    addAll(child.getSubViewsByType(tClass))
                }
                if (tClass.isInstance(child))
                    add(tClass.cast(child))
            }
        }.filterNotNull()
    }
    return mutableListOf<T?>().apply {
        //Adding main view also if it is of the provided type
        if (tClass.isInstance(this@getViewsByType)) {
            add(tClass.cast(this@getViewsByType))
        }
        addAll(getSubViewsByType(tClass))
    }.filterNotNull()
}

In the activity,

val listOfViews=(binding.root as ViewGroup).getViewsByType(CustomLayout::class.java)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.