Android find child views by class

I needed to get all the buttons that were descendants of a view so I’ve created another small Android utility function to do it.

It returns a list of all child views that are an instance of the specified class (including all the children of child views):


import android.view.View
import android.view.ViewGroup

object AndroidUtils {
    fun <T : View> getChildViewsByClass(parent: ViewGroup, clazz: Class<T>): ArrayList<T> {
        val children = ArrayList<T>()

        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)

            if (clazz.isInstance(child)) {
                children.add(child as T)
            } else if (child is ViewGroup) {
                children.addAll(getChildViewsByClass(child, clazz))

        return children