Android | Get all children elements of a ViewGroup

后端 未结 7 1526
星月不相逢
星月不相逢 2020-12-08 02:56

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

相关标签:
7条回答
  • 2020-12-08 03:21

    (source)

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

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

    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.

    0 讨论(0)
提交回复
热议问题