為了更易于使用SharedPreferences馏臭,使用Koltin的委托模式來(lái)對(duì)SP進(jìn)行封裝
1. 定義委托類(lèi)
class Preference<T>(private val key: String, private val default: T): ReadWriteProperty<Any?, T> {
private val prefs: SharedPreferences by lazy { MyApp.instance!!.applicationContext.getSharedPreferences("SP", Context.MODE_PRIVATE) }
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return with(prefs) {
when(default) {
is Int -> getInt(key, default)
is Float -> getFloat(key, default)
is Long -> getLong(key, default)
is Boolean -> getBoolean(key, default)
is String -> getString(key, default)
else -> throw IllegalArgumentException("SharedPreference can't be get this type")
} as T
}
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
with(prefs.edit()) {
when(value) {
is Int -> putInt(key, value)
is Float -> putFloat(key, value)
is Long -> putLong(key, value)
is Boolean -> putBoolean(key, value)
is String -> putString(key, value)
else -> throw IllegalArgumentException("SharedPreference can't be save this type")
}.apply()
}
}
}
2.簡(jiǎn)單使用
/**
* 是否顯示引導(dǎo)頁(yè)
*/
var guideEnable by Preference("guideEnable", true)