How to get all Views in an Activity?

Viewed 21711

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 something like

for (View v : this)
{
     //do something with the views 
     //depending on the types (button, image , etc)
}
5 Answers

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.

Nice way to do this in Kotlin recursivelly:

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

    return children
            .toList()
            .flatMap { it.getAllViews() }
            .plus(this as View)
}
Related