Last active
December 1, 2020 16:04
-
-
Save green-nick/e394f8b28e41b1965a23cb77a9ebdc71 to your computer and use it in GitHub Desktop.
Delegates for easier view init in Activities and Fragments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity | |
import androidx.annotation.IdRes | |
import androidx.fragment.app.Fragment | |
import android.view.View | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleEventObserver | |
import kotlin.properties.ReadOnlyProperty | |
import kotlin.reflect.KProperty | |
fun <V : View> Activity.view(@IdRes viewId: Int) = lazy<V>(LazyThreadSafetyMode.NONE) { findViewById(viewId) } | |
fun <V : View> Fragment.view(@IdRes viewId: Int) = object : ReadOnlyProperty<Fragment, V> { | |
private var cached: V? = null | |
private val lifecycleListener = LifecycleEventObserver { _, event -> | |
if (event == Lifecycle.Event.ON_DESTROY) { | |
cached = null | |
} | |
} | |
init { | |
viewLifecycleOwner.lifecycle.addObserver(lifecycleListener) | |
} | |
override fun getValue(thisRef: Fragment, property: KProperty<*>): V = | |
cached ?: requireView().findViewById<V>(viewId).also { cached = it } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment