william
06/12/2019, 4:34 PMonDestroy
or something similar? the manual useage of a nullable view seems very un-kotlintseisel
06/12/2019, 6:50 PMinline fun <reified V : View> view(viewId: Int) = ViewDelegate<V>(viewId)
class ViewDelegate<out V : View>(private val viewId: Int) : ReadOnlyProperty<Fragment, V> {
private var viewRef: V? = null
override fun getValue(thisRef: Fragment, property: KProperty<*>): V {
return viewRef ?: run {
thisRef.view?.findViewById<V>(viewId)?.also {
viewRef = it
thisRef.lifecycle.addObserver(DestroyViewObserver())
} ?: error("This fragment does not have a view, or its view has not been created yet.")
}
}
private inner class DestroyViewObserver : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
viewRef = null
owner.lifecycle.removeObserver(this)
}
}
}
Usage in a Fragment subclass :
private val myText by view<TextView>(R.id.my_text)
This is a lazy and cached call to findViewById
on a fragment. The reference is automatically dropped when Fragment
is destroyed. I don't think that's better than Kotlin Android Extensions though.william
06/12/2019, 8:55 PMitnoles
06/13/2019, 3:23 AM