Kotlin对SP使用的封装
2018-08-29 本文已影响32人
kermitye
为了更易于使用SharedPreferences,使用Koltin的委托模式来对SP进行封装
1. 定义委托类
class Preference<T>(val name: String, val default: T) {
val prefs: SharedPreferences by lazy { MyApp.instance.applicationContext.getSharedPreferences("SP", Context.MODE_PRIVATE) }
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = getSharedPreferences(name, default)
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = putSharedPreferences(name, value)
private fun putSharedPreferences(name: String, value: T) = with(prefs.edit()) {
when(value) {
is Int -> putInt(name, value)
is Float -> putFloat(name, value)
is Long -> putLong(name, value)
is Boolean -> putBoolean(name, value)
is String -> putString(name, value)
else -> throw IllegalArgumentException("SharedPreference can't be save this type")
}.apply()
}
private fun getSharedPreferences(name:String, default: T): T = with(prefs) {
val res: Any = when(default) {
is Int -> getInt(name, default)
is Float -> getFloat(name, default)
is Long -> getLong(name, default)
is Boolean -> getBoolean(name, default)
is String -> getString(name, default)
else -> throw IllegalArgumentException("SharedPreference can't be get this type")
}
return res as T
}
}
2. 定义使用的静态方法
object DelegatesExt {
fun <T> preference(name: String, default: T) = Preference(name, default)
}
3.简单使用
var mGuideEnable by DelegatesExt.preference("guide", false)