https://kotlinlang.org logo
#android
Title
# android
w

william

06/12/2019, 4:34 PM
does anyone use some type of delegate to hold onto referenced views in a weak fashion / null them out in
onDestroy
or something similar? the manual useage of a nullable view seems very un-kotlin
t

tseisel

06/12/2019, 6:50 PM
I just wrote this :
Copy code
inline 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 :
Copy code
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.
👍 2
w

william

06/12/2019, 8:55 PM
interesting. i wonder how kotlin android extensions work under the hood
i

itnoles

06/13/2019, 3:23 AM
it used Hashmap to caches views.