Kotlin对SP使用的封装

为了更易于使用SharedPreferences,使用Koltin的委托模式来对SP进行封装

1. 定义委托类

class Preference(private val key: String, private val default: T): ReadWriteProperty {

    private val prefs: SharedPreferences by lazy { MyApp.instance!!.applicationContext.getSharedPreferences("SP", Context.MODE_PRIVATE) }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return with(prefs) {
            when(default) {
                is Int -> getInt(key, default)
                is Float -> getFloat(key, default)
                is Long -> getLong(key, default)
                is Boolean -> getBoolean(key, default)
                is String -> getString(key, default)
                else -> throw IllegalArgumentException("SharedPreference can't be get this type")
            } as T
        }

    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        with(prefs.edit()) {
            when(value) {
                is Int -> putInt(key, value)
                is Float -> putFloat(key, value)
                is Long -> putLong(key, value)
                is Boolean -> putBoolean(key, value)
                is String -> putString(key, value)
                else -> throw IllegalArgumentException("SharedPreference can't be save this type")
            }.apply()
        }
    }

}

2.简单使用

/**
  * 是否显示引导页
*/
var guideEnable by Preference("guideEnable", true)

你可能感兴趣的:(Kotlin对SP使用的封装)