Skip to content

Instantly share code, notes, and snippets.

@punksta
Created April 8, 2017 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save punksta/c401232731939bc7bb0406caa1b8eccc to your computer and use it in GitHub Desktop.
Save punksta/c401232731939bc7bb0406caa1b8eccc to your computer and use it in GitHub Desktop.
Providing a delegate kotlin 1.1
class MyActivity : AppCompatActivity() {
private val d: TextView by findRes(R.id.action_bar)
}
class ResourceLoader<out V>(val id: Int) {
private var cache : V? = null
private var rootView: View? = null
operator fun provideDelegate(
thisRef: Activity,
prop: KProperty<*>
) : ReadOnlyProperty<Activity, V> {
return object : ReadOnlyProperty<Activity, V> {
override fun getValue(thisRef: Activity, property: KProperty<*>): V {
val currentRootView = thisRef.findViewById(android.R.id.content)
val localCache = cache
return when {
currentRootView != localCache || localCache == null -> {
(currentRootView.findViewById(id) as V).also {
cache = it
rootView = currentRootView
}
}
else -> localCache
}
}
}
}
}
fun <V: View> Activity.findRes(@IntegerRes id: Int) = ResourceLoader<V>(id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment