Created
January 6, 2022 07:42
-
-
Save cesclong/236b2cc8824ed9b1991b003d7258549b to your computer and use it in GitHub Desktop.
使用委托类实现简化SharedPreference的使用
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 PreDelegate<T>( | |
private val name: String, | |
private val default: T, | |
private val isCommit: Boolean = false, | |
private val prefs: SharedPreferences | |
) { | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): T { | |
return getPref(name, default) ?: default | |
} | |
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { | |
value?.let { | |
putPref(name, value) | |
} | |
} | |
private fun <T> getPref(name: String, defalut: T?) = with(prefs) { | |
val result: Any? = when (defalut) { | |
is Long -> getLong(name, defalut) | |
is String -> getString(name, defalut) | |
is Int -> getInt(name, defalut) | |
is Boolean -> getBoolean(name, defalut) | |
is Float -> getFloat(name, defalut) | |
else -> throw IllegalArgumentException("This type is not supported") | |
} | |
result as? T | |
} | |
private fun <T> putPref(name: String, value: T) = with(prefs.edit()) { | |
when (value) { | |
is Long -> putLong(name, value) | |
is String -> putString(name, value) | |
is Int -> putInt(name, value) | |
is Boolean -> putBoolean(name, value) | |
is Float -> putFloat(name, value) | |
else -> throw IllegalArgumentException("This type is not supported") | |
} | |
if (isCommit) { | |
commit() | |
} else { | |
apply() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment