为了更易于使用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 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦