为了更易于使用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)
作者:kermitye
链接:https://www.jianshu.com/p/861c17162039
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦