Skip to content

Instantly share code, notes, and snippets.

@Hasiy
Created July 3, 2020 09:35
Show Gist options
  • Save Hasiy/08230554fc6d5e7361f429465f7fd8a9 to your computer and use it in GitHub Desktop.
Save Hasiy/08230554fc6d5e7361f429465f7fd8a9 to your computer and use it in GitHub Desktop.
SharedPreferenceDelegate
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* @author : Hasiy
* @date : 2020/7/1 14:31
* @desc : SharedPreferenceDelegate
* @use : var someValue : Boolean by SharedPreferenceDelegate(Application), "someValue", defaultValue=false)
*/
class SharedPreferenceDelegate<T>(
private val context: Context,
private val name: String,
private val defaultValue: T,
private val prefName: String = context.packageName + "_preferences"
) :
ReadWriteProperty<Any?, T> {
private val prefs: SharedPreferences by lazy {
context.getSharedPreferences(prefName, Context.MODE_PRIVATE)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
println("setValue from delegate")
return getPreference(key = name)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
println("setValue from delegate")
putPreference(key = name, value = value)
}
@Suppress("UNCHECKED_CAST")
private fun getPreference(key: String): T {
@Suppress("IMPLICIT_CAST_TO_ANY")
return when (defaultValue) {
is String -> prefs.getString(key, defaultValue)
is Long -> prefs.getLong(key, defaultValue)
is Boolean -> prefs.getBoolean(key, defaultValue)
is Float -> prefs.getFloat(key, defaultValue)
is Int -> prefs.getInt(key, defaultValue)
else -> throw IllegalArgumentException("Unknown Type.")
} as T
}
private fun putPreference(key: String, value: T) = with(prefs.edit()) {
when (value) {
is String -> putString(key, value)
is Long -> putLong(key, value)
is Boolean -> putBoolean(key, value)
is Float -> putFloat(key, value)
is Int -> putInt(key, value)
else -> throw IllegalArgumentException("Unknown Type.")
}
}.apply()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment