Kotlin Recursive Extension Function To Walk Android View Hierarchy
I am attempting to create a generic extension function that can walk an Android view hierarchy and return the first occurence of a view of a specific type. The idea would be to in
Solution 1:
I'm gonna add a little bit to Victor Rendina's answer.
You can have two functions: one with the clazz: Class<T>
parameter and the other one inline with reified generic:
inlinefun<reified T : View> View.findFirstChildRecursive(): T? {
return findFirstChildRecursive(T::class.java)
}
fun<T: View> View.findFirstChildRecursive(clazz: Class<T>): T? {
if (this::class.java == clazz) {
@Suppress("UNCHECKED_CAST")returnthisas T
} elseif (thisis ViewGroup) {
for (i in0 until childCount) {
getChildAt(i).findFirstChildRecursive(clazz)?.let { return it }
}
}
returnnull
}
Solution 2:
Basically the bottom line is Kotlin doesn't allow you to inline recursive functions because it could potentially have to inline an infinite number of calls.
See this related post:Can a recursive function be inline?
The method above also can not be a tailrec
function because calling itself is not the last operation in the function.
See the Kotlin function docs here:https://kotlinlang.org/docs/reference/functions.html
If you still want to achieve something similar, you can pass the class into the function.
val someView = parentView.findFirstChildRecursive(Toolbar::class.java)
fun<T: View> View.findFirstChildRecursive(clazz: Class<T>): T? {
if (this::class.java == clazz) {
@Suppress("UNCHECKED_CAST")returnthisas T
} elseif (thisis ViewGroup) {
for (i in0 until childCount) {
getChildAt(i).findFirstChildRecursive(clazz)?.let { return it }
}
}
returnnull
}
Post a Comment for "Kotlin Recursive Extension Function To Walk Android View Hierarchy"