Loop through all subviews of an Android view?

后端 未结 5 1398
北荒
北荒 2020-12-08 04:48

I’m working on a game for Android. To help implement it, my idea is to create a subclass of a view. I would then insert several instances of this class as children of the ma

5条回答
  •  攒了一身酷
    2020-12-08 05:17

    I have made a small example of a recursive function:

    public void recursiveLoopChildren(ViewGroup parent) {
            for (int i = 0; i < parent.getChildCount(); i++) {
                final View child = parent.getChildAt(i);
                if (child instanceof ViewGroup) {
                    recursiveLoopChildren((ViewGroup) child);
                    // DO SOMETHING WITH VIEWGROUP, AFTER CHILDREN HAS BEEN LOOPED
                } else {
                    if (child != null) {
                        // DO SOMETHING WITH VIEW
                    }
                }
            }
        }
    

    The function will start looping over al view elements inside a ViewGroup (from first to last item), if a child is a ViewGroup then restart the function with that child to retrieve all nested views inside that child.

提交回复
热议问题