递归查找给定根视图的所有子视图

Pra*_*eep 3 android android-layout

我想找到给定根视图的所有子视图.

public List<View> getAllChildViews(View rootView)
{
    //return all child views for given rootView recursively
}
Run Code Online (Sandbox Code Playgroud)

此方法的使用者将通过rootView,如下所示

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

我可以将cast rootView键入特定的布局,然后获取所有子级(在叶级别),但我不确定根视图的类型.它可以是ScrollView或任何不同的布局

Kev*_*OUX 13

此解决方案的 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
}
Run Code Online (Sandbox Code Playgroud)

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


Pra*_*eep 6

 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;
    }
Run Code Online (Sandbox Code Playgroud)