Skip to content

Instantly share code, notes, and snippets.

@HarryTylenol
Last active September 12, 2018 07:36
Show Gist options
  • Save HarryTylenol/e3ac042d0c7295d80e5d7ba363391da9 to your computer and use it in GitHub Desktop.
Save HarryTylenol/e3ac042d0c7295d80e5d7ba363391da9 to your computer and use it in GitHub Desktop.
class DelegatedPreference<T>(val context: Context, val default: T) : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return context.defaultSharedPreferences.run {
when (default) {
is String -> getString(property.name, default)
is Long -> getLong(property.name, default)
is Int -> getInt(property.name, default)
is Boolean -> getBoolean(property.name, default)
else -> null
} as T
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
context.defaultSharedPreferences.edit().apply {
when (value) {
is String -> putString(property.name, value)
is Long -> putLong(property.name, value)
is Int -> putInt(property.name, value)
is Boolean -> putBoolean(property.name, value)
}
}.apply()
}
}
class MainActivity : BaseActivity() {
// ...
private var pref_is_enabled by DelegatedPreference(this /** Context **/ , false)
private fun onSwitchClicked(value : Boolean) {
pref_is_enabled = value // Save ["pref_is_enabled" : $value] preference automatically
ui.switch.isChecked = pref_is_enabled // Fetch "pref_is_enabled" preference value automatically
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment