package cn.flightfeather.thirdapp.util
|
|
import android.content.Context
|
import android.content.SharedPreferences
|
import cn.flightfeather.thirdapp.CommonApplication
|
import kotlin.reflect.KProperty
|
|
/**
|
* SharedPreference对象
|
* @author riku
|
* Date: 2019/4/9
|
*/
|
class MyPreference<T>(private val keyName: String, private val default: T) {
|
|
private val prefs:SharedPreferences by lazy { CommonApplication.getInstance().getSharedPreferences("preference", Context.MODE_PRIVATE)}
|
|
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
|
return findSharedPreferences(keyName, default)
|
}
|
|
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
|
putSharedPreferences(keyName, value)
|
}
|
|
fun get(): T {
|
return findSharedPreferences(keyName, default)
|
}
|
|
fun set(value: T) {
|
putSharedPreferences(keyName, value)
|
}
|
|
@Suppress("UNCHECKED_CAST")
|
private fun findSharedPreferences(name: String, default: T): T = with(prefs) {
|
val res: Any = when (default) {
|
is Long -> getLong(name, default)
|
is String -> getString(name, default)
|
is Int -> getInt(name, default)
|
is Boolean -> getBoolean(name, default)
|
is Float -> getFloat(name, default)
|
else -> throw IllegalArgumentException("Type Error, cannot be got!")
|
}
|
|
return res as T
|
}
|
|
private fun putSharedPreferences(name: String, value: T) = with(prefs.edit()) {
|
when (value) {
|
is Long -> putLong(name, value)
|
is String -> putString(name, value)
|
is Int -> putInt(name, value)
|
is Boolean -> putBoolean(name, value)
|
is Float -> putFloat(name, value)
|
else->throw IllegalArgumentException("Type Error, cannot be saved!")
|
}.apply()
|
}
|
}
|