Loop through all subviews of an Android view?

…衆ロ難τιáo~ 提交于 2019-11-28 04:56:11
Romain Guy

@jqpubliq Is right but if you really want to go through all Views you can simply use the getChildCount() and getChildAt() methods from ViewGroup. A simple recursive method will do the rest.

Tobrun

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.

Using Views sounds like its going to be brutally difficult to render anything well if there is movement. You probably want to be drawing to a Canvas or using OpenGL unless you're doing something really static. Here's a great talk from last years I/O conference on making Android games. Its kind of long and you can skip about 15 minutes in. Also the source is available. That should give you a good idea of ways to go about things

The alternative

public static void recursivelyFindChildren(View view) {
    if (view instanceof ViewGroup) {
        //ViewGroup
        ViewGroup viewGroup = (ViewGroup)view;

        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            recursivelyFindChildren(viewGroup.getChildAt(i));
        }

    } else {
        //View
    }

}

Or you can return something you can use the next approach

@Nullable
private static WebView recursivelyFindWebView(View view) {
    if (view instanceof ViewGroup) {
        //ViewGroup
        ViewGroup viewGroup = (ViewGroup)view;

        if (!(viewGroup instanceof WebView)) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                WebView result = recursivelyFindWebView(viewGroup.getChildAt(i));

                if (result != null) {
                    return result;
                }
            }
        } else {
            //WebView

            WebView webView = (WebView)viewGroup;
            return webView;
        }

    }

    return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!