继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Kotlin对SP使用的封装

慕码人8056858
关注TA
已关注
手记 1092
粉丝 350
获赞 1320

为了更易于使用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


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP