安卓|让所有孩子的ViewGroup元素 [英] Android | Get all children elements of a ViewGroup

查看:155
本文介绍了安卓|让所有孩子的ViewGroup元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getChildAt(i)在得到了的ViewGroup的只有直接子女,是否有可能访问到所有的孩子没有做嵌套循环?

getChildAt(i) on gets only the direct children of a ViewGroup, is it possible to access to all children without doing nested loops?

推荐答案

如果你想获得的所有儿童的意见,以及儿童中的意见 ViewGroups ,你必须这样做递归,由于在API中没有规定这样做的开箱即用。

If you want to get all the child views, as well as the views within children ViewGroups, you must do it recursively, since there is no provision in the API to do this out of the box.

private ArrayList<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);

        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        viewArrayList.addAll(getAllChildren(child));

        result.addAll(viewArrayList);
    }
    return result;
}

这会给你在层次结构中的所有视图,然后可以遍历一个ArrayList

This will give you an ArrayList with all the Views in the hierarchy which you can then iterate over.

本质上讲,这code调用自身,如果它发现另一个的ViewGroup在层次结构中,然后返回一个ArrayList要加入到更大的ArrayList

Essentially, this code call itself if it finds another ViewGroup in the hierarchy, and then returns an ArrayList to be added to the bigger ArrayList.

这篇关于安卓|让所有孩子的ViewGroup元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆