Last active
September 12, 2018 07:36
-
-
Save HarryTylenol/e3ac042d0c7295d80e5d7ba363391da9 to your computer and use it in GitHub Desktop.
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 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() | |
} | |
} |
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 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