美文网首页Android技术知识Android开发Android开发经验谈
使用kotlin特性简单封装SharedPreferences

使用kotlin特性简单封装SharedPreferences

作者: 刚刚了然 | 来源:发表于2018-11-16 11:30 被阅读19次

    使用方法

    object AccountBiz{
        var username by defSP("")
        var mobil:String by defSP("mobil", "")
    }
    
    //取值
    val name=AccountBiz.username
    //存值
    AccountBiz.username="aaaaa"
    

    SPUtil实现

    const val SPFileName = "Setting"
    /**
     * 使用defSP的话key为""在SPUtil中key会赋值成变量名
     * 所以一般用这个
     */
    inline fun <reified R, T> R.defSP(default: T) = defSP("", default)
    /**
     * 指定key用这个
     */
    inline fun <reified R, T> R.defSP(key: String, default: T) = SPUtil(key, default, R::class.java.name)
    
    class SPUtil<T>(val key: String, val defValue: T, val fileName: String = SPFileName) : ReadWriteProperty<Any?, T> {
        val sp by lazy {
            appContext.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        }
    
        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            val temKey = if (key.isEmpty()) property.name else key
            return when (defValue) {
                is String -> sp.getString(temKey, defValue)
                is Boolean -> sp.getBoolean(temKey, defValue)
                is Int -> sp.getInt(temKey, defValue)
                is Float -> sp.getFloat(temKey, defValue)
                is Long -> sp.getLong(temKey, defValue)
                else -> throw IllegalArgumentException("类型错误")
            } as T
        }
    
        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            val temKey = if (key.isEmpty()) property.name else key
            with(sp.edit()) {
                when (value) {
                    is String -> putString(temKey, value)
                    is Boolean -> putBoolean(temKey, value)
                    is Int -> putInt(temKey, value)
                    is Float -> putFloat(temKey, value)
                    is Long -> putLong(temKey, value)
                    else -> throw IllegalArgumentException("类型错误")
                }
                commit()
            }
        }
    }
    
    fun cleanSP(fileName: String = SPFileName) {
        appContext.getSharedPreferences(fileName, Context.MODE_PRIVATE).edit().clear().commit()
    }
    

    相关文章

      网友评论

        本文标题:使用kotlin特性简单封装SharedPreferences

        本文链接:https://www.haomeiwen.com/subject/isopfqtx.html