Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all child views for given root view recursively

I want to find all child views for given root view.

public List<View> getAllChildViews(View rootView)
{
    //return all child views for given rootView recursively
}

Consumer of this method will pass rootView as follows

//client has some Custom View
List<View> childViews = getAllChildViews(customView.getRootView());  //get root view of custom view

I can type cast rootView to particular layout and then get all children ( at leaf level ) but I am not sure what will be the type of root view. It can be ScrollView or any different layout

like image 775
Pradeep Avatar asked Oct 30 '15 22:10

Pradeep


2 Answers

Kotlin extension for this solution:

fun View.getAllChildren(): List<View> {
    val result = ArrayList<View>()
    if (this !is ViewGroup) {
        result.add(this)
    } else {
        for (index in 0 until this.childCount) {
            val child = this.getChildAt(index)
            result.addAll(child.getAllChildren())
        }
    }
    return result
}

Just call myView.getAllChildren() on any view

like image 86
Kevin ABRIOUX Avatar answered Nov 14 '22 23:11

Kevin ABRIOUX


 private List<View> getAllChildren(View v) {

        if (!(v instanceof ViewGroup)) {
            ArrayList<View> viewArrayList = new ArrayList<View>();
            viewArrayList.add(v);
            return viewArrayList;
        }

        ArrayList<View> result = new ArrayList<View>();

        ViewGroup viewGroup = (ViewGroup) v;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {

            View child = viewGroup.getChildAt(i);

            //Do not add any parents, just add child elements
            result.addAll(getAllChildren(child));
        }
        return result;
    }
like image 40
Pradeep Avatar answered Nov 15 '22 01:11

Pradeep