所以我对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
。 最佳答案
为什么在特定情况下使用afterMeasure
?
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))
}
}
}
}
Log.i()
替换了println()
记录器:tabs.allViewsOfType<Button> {
println("Dale: ${it.text}")
}
I/System.out: Dale: Button 4
Dale: Button 3
Dale: Button 2
Dale: Button 1