Find all child views for given root view recursively

时间:2015-10-30 22:57:41

标签: android android-layout

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

3 个答案:

答案 0 :(得分:5)

 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;
    }

答案 1 :(得分:2)

此解决方案的 Kotlin 扩展:

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
}

只需在任何视图上调用 myView.getAllChildren()

答案 2 :(得分:1)

Why don't you create a method such as:

public List<View> getAllChildViews(View view)
{
    if (view instanceof ViewGroup)
       {
          ViewGroup vg = (ViewGroup) view;

          for (int i = 0; i < vg.getChildCount(); i++) {

               View subView = vg.getChildAt(i);
          }
       }
}