Enumerate/Iterate all Views in Activity?

后端 未结 8 570
忘了有多久
忘了有多久 2020-12-09 17:33

Is there a way to iterate through all the views in your Activity? Something like:

Iterator it = getViewIterator();
...

Does this exi

8条回答
  •  轮回少年
    2020-12-09 17:50

    Small recursive function which does enumerating all views

     private fun processAllViews(viewGroup: ViewGroup) {
        for (child in viewGroup.children) {
            if (child is EditText) {
               // do some stuff with EditText
            } else if (child !is ViewGroup) {
                // do some stuff with not EditText and not ViewGroup
            } else {
                processAllViews(child as ViewGroup) // process inner layout
            }
        }
    }
    

    Written in Kotlin.

    To use this function:

    processAllViews( [~rootLayoutId~] )
    

    or if you don't have / don't want root layout id

    val baseContent = (findViewById(android.R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
    processAllViews(baseContent)
    

提交回复
热议问题