Kotlin / Android:递归查找所有T型视图

时间:2018-10-18 01:44:27

标签: android recursion kotlin stack extension-function

所以我有ViewGroup的扩展功能:

inline fun <reified T : View> ViewGroup.allViewsOfType(action: (T) -> Unit) 
{
    val views = Stack<View>()

    afterMeasured {
        views.addAll((0 until childCount).map(this::getChildAt))
    }

    while (!views.isEmpty()) {
        views.pop().let {
            if (it is T) action(it)
            if (it is ViewGroup) {
                afterMeasured {
                    views.addAll((0 until childCount).map(this::getChildAt))
                }
            }
        }
    }
}

我这样使用它:

tabs.allViewsOfType<Button> { Log.i("Dale", it.text.toString()) }

但是以某种方式不起作用。我做错了什么吗?

顺便说一句,tabs是一个LinearLayout,其中包含三个Button

1 个答案:

答案 0 :(得分:0)

在特殊情况下为什么要使用afterMeasure

  1. 我刚刚删除了afterMeasure

    inline fun <reified T : View> ViewGroup.allViewsOfType(action: (T) -> Unit) {
        val views = Stack<View>()
    
        views.addAll((0 until childCount).map(this::getChildAt))
    
        while (!views.isEmpty()) {
            views.pop().let {
                if (it is T) action(it)
                if (it is ViewGroup) {
                    views.addAll((0 until childCount).map(this::getChildAt))
                }
            }
        }
    }
    
  2. 用简单的Kotlin的Log.i()代替了println()记录器:

    tabs.allViewsOfType<Button> {
        println("Dale: ${it.text}")
    }
    
  3. 现在您的函数运行正常:

    I/System.out: Dale: Button 4
                  Dale: Button 3
                  Dale: Button 2
                  Dale: Button 1