Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.content.SharedPreferences
- import kotlin.properties.ReadWriteProperty
- import kotlin.reflect.KFunction3
- import kotlin.reflect.KProperty
- @Suppress("UNCHECKED_CAST")
- fun <T> sharedPreferences(sharedPreferences: SharedPreferences, key: String, defaultValue: T): SharedPreferencesProperty<T> =
- when (defaultValue) {
- is Boolean -> SharedPreferencesProperty(sharedPreferences, key, defaultValue,
- SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean)
- as SharedPreferencesProperty<T>
- is Float -> SharedPreferencesProperty(sharedPreferences, key, defaultValue,
- SharedPreferences::getFloat, SharedPreferences.Editor::putFloat)
- as SharedPreferencesProperty<T>
- is Int -> SharedPreferencesProperty(sharedPreferences, key, defaultValue,
- SharedPreferences::getInt, SharedPreferences.Editor::putInt)
- as SharedPreferencesProperty<T>
- is Long -> SharedPreferencesProperty(sharedPreferences, key, defaultValue,
- SharedPreferences::getLong, SharedPreferences.Editor::putLong)
- as SharedPreferencesProperty<T>
- is String -> SharedPreferencesProperty(sharedPreferences, key, defaultValue,
- SharedPreferences::getString, SharedPreferences.Editor::putString)
- as SharedPreferencesProperty<T>
- is Set<*> -> SharedPreferencesProperty(sharedPreferences, key, defaultValue as Set<String>,
- SharedPreferences::getStringSet, SharedPreferences.Editor::putStringSet)
- as SharedPreferencesProperty<T>
- else -> throw IllegalStateException("Illegal property type: ${(defaultValue as Any).javaClass}")
- }
- open class SharedPreferencesProperty<T>(
- private val sharedPreferences: SharedPreferences,
- val key: String,
- val defaultValue: T,
- val getValue: KFunction3<SharedPreferences, String, T, T>,
- val setValue: KFunction3<SharedPreferences.Editor, String, T, SharedPreferences.Editor>)
- : ReadWriteProperty<Any, T> {
- override fun getValue(thisRef: Any, property: KProperty<*>): T =
- getValue(sharedPreferences, key, defaultValue)
- override fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
- setValue(sharedPreferences.edit(), key, value).apply()
- }
Add Comment
Please, Sign In to add comment