Skip to content Skip to sidebar Skip to footer

How To Get All Views In An Activity?

is there a way to get every view that is inside my activity? I have over 200 views including buttons, and images, so i want to be able to access them by using a loop for example so

Solution 1:

is there a way to get every view that is inside my activity?

Get your root View, cast it to a ViewGroup, call getChildCount() and getChildAt(), and recurse as needed.

I have over 200 views including buttons, and images, so i want to be able to access them by using a loop

That is a rather large number of Views.

Solution 2:

To be specific:

privatevoidshow_children(View v) {
    ViewGroup viewgroup=(ViewGroup)v;
    for (int i=0;i<viewgroup.getChildCount();i++) {
        View v1=viewgroup.getChildAt(i);
        if (v1 instanceof ViewGroup) show_children(v1);
        Log.d("APPNAME",v1.toString());
    }
}

And then use the function somewhere:

show_children(getWindow().getDecorView());

to show all Views in the current Activity.

Solution 3:

Try to find all view associated with the Activity.

give the following command.

ViewGroup viewgroup=(ViewGroup)view.getParent();
viewgroup.getchildcount();

iterate through the loop.

We will get the Result.

Solution 4:

You can use the hierarchyviewer, It allows you to see the view hierarchy including those created in code. It's primary reason is for debugging things like this. The latest Android Studio now has this feature in the Device Monitor that lets you make a dump of the UI to debug it.

Solution 5:

Nice way to do this in Kotlin recursivelly:

privatefun View.getAllViews(): List<View> {
    if (this !is ViewGroup || childCount == 0) return listOf(this)

    return children
            .toList()
            .flatMap { it.getAllViews() }
            .plus(thisas View)
}

Post a Comment for "How To Get All Views In An Activity?"