Created
April 8, 2017 18:19
-
-
Save punksta/c401232731939bc7bb0406caa1b8eccc to your computer and use it in GitHub Desktop.
Providing a delegate kotlin 1.1
This file contains 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
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