SharedPreferences 属性代理
来源:7-5 案例:使用属性代理读写 Properties
 
			wdmzjgxd
2020-09-28
class SharedPreferencesDelegate<T>(
    private val sharedPreferences: SharedPreferences,
    private val editor: SharedPreferences.Editor,
    private val default: T,
) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return with(sharedPreferences) {
            val result = when (default) {
                is Boolean -> getBoolean(property.name, default)
                is Int -> getInt(property.name, default)
                is Long -> getLong(property.name, default)
                is String -> getString(property.name, default)
                is Float -> getFloat(property.name, default)
                else -> throw IllegalArgumentException("error type of defaultValue")
            }
            result as T
        }
    }
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        editor.apply {
            when (value) {
                is Boolean -> putBoolean(property.name, value)
                is Int -> putInt(property.name, value)
                is Long -> putLong(property.name, value)
                is String -> putString(property.name, value)
                is Float -> putFloat(property.name, value)
                else -> throw IllegalArgumentException("error type of value")
            }.apply()
        }
    }
}
abstract class AbsSp {
    private val sharedPreferences by lazy {
        MyApplication.instance!!.applicationContext.getSharedPreferences(this::class.simpleName!!, Context.MODE_PRIVATE)
    }
    private val editor by lazy {
        sharedPreferences.edit()
    }
    fun <T> default(default: T): SharedPreferencesDelegate<T> {
        return SharedPreferencesDelegate(sharedPreferences, editor, default)
    }
}
object DefaultSp : AbsSp()
object GlobalSp : AbsSp()
我自己尝试实现了一下,想看下老师写的,没找到在哪里
写回答
	1回答
- 
				  bennyhuo 2020-09-28 可以在课程源码的android工程里面找找,如果没有,后面我加一下 022024-09-01
相似问题
