Skip to content

Instantly share code, notes, and snippets.

@burntcookie90
Last active April 26, 2018 19:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burntcookie90/6356a0f05a7223335f26b08cd788a065 to your computer and use it in GitHub Desktop.
Save burntcookie90/6356a0f05a7223335f26b08cd788a065 to your computer and use it in GitHub Desktop.
import android.app.Activity
import android.app.Fragment
import android.support.annotation.BoolRes
import android.support.annotation.StringRes
import android.support.v4.app.DialogFragment
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
//region Boolean
fun Activity.bindBool(@BoolRes id: Int) : ReadOnlyProperty<Activity, Boolean> =
required(id, booleanGetter)
fun Fragment.bindBool(@BoolRes id: Int) : ReadOnlyProperty<Fragment, Boolean> =
required(id, booleanGetter)
fun DialogFragment.bindBool(@BoolRes id: Int) : ReadOnlyProperty<DialogFragment, Boolean> =
required(id, booleanGetter)
private val Activity.booleanGetter: Activity.(Int) -> Boolean
get() = { resources.getBoolean(it) }
private val Fragment.booleanGetter: Fragment.(Int) -> Boolean
get() = { resources.getBoolean(it) }
private val DialogFragment.booleanGetter: DialogFragment.(Int) -> Boolean
get() = { resources.getBoolean(it) }
//endregion
// region String
fun Activity.bindString(@StringRes id: Int) : ReadOnlyProperty<Activity, String> =
required(id, stringGetter)
fun Fragment.bindString(@StringRes id: Int) : ReadOnlyProperty<Fragment, String> =
required(id, stringGetter)
fun DialogFragment.bindString(@StringRes id: Int) : ReadOnlyProperty<DialogFragment, String> =
required(id, stringGetter)
private val Activity.stringGetter: Activity.(Int) -> String
get() = { resources.getString(it) }
private val Fragment.stringGetter: Fragment.(Int) -> String
get() = { resources.getString(it) }
private val DialogFragment.stringGetter: DialogFragment.(Int) -> String
get() = { resources.getString(it) }
//endregion
//region utility
private fun <T, V> required(id: Int, getter: T.(Int) -> V)
= Lazy { t: T, desc -> t.getter(id) ?: resourceNotFound(id, desc) }
private fun resourceNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("Resource ID $id for '${desc.name}' not found.")
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
// From kotterknife
private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
//endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment