How to get all Views in an Activity?

后端 未结 5 640
太阳男子
太阳男子 2020-12-18 23:21

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

5条回答
  •  旧时难觅i
    2020-12-18 23:49

    Nice way to do this in Kotlin recursivelly:

    private fun View.getAllViews(): List {
        if (this !is ViewGroup || childCount == 0) return listOf(this)
    
        return children
                .toList()
                .flatMap { it.getAllViews() }
                .plus(this as View)
    }
    

提交回复
热议问题