@@ -2,6 +2,7 @@ package moe.feng.kotlinyan.common
22
33import android.annotation.SuppressLint
44import android.content.Intent
5+ import android.content.SharedPreferences
56import android.os.Build
67import android.os.Bundle
78import android.os.IBinder
@@ -150,4 +151,25 @@ interface AndroidExtensions : ActivityExtensions, ViewExtensions, ResourcesExten
150151 }
151152 }
152153
154+ operator fun SharedPreferences.get (key : String ): SharedPreferencesGetter ?
155+ = if (contains(key)) SharedPreferencesGetter (this , key) else null
156+
157+ class SharedPreferencesGetter internal constructor(private val sp : SharedPreferences , val key : String ) {
158+ fun asString (defValue : String? = null): String = sp.getString(key, defValue)
159+ fun asInt (defValue : Int = 0): Int = sp.getInt(key, defValue)
160+ fun asBoolean (defValue : Boolean = false): Boolean = sp.getBoolean(key, defValue)
161+ fun asLong (defValue : Long = 0): Long = sp.getLong(key, defValue)
162+ fun asFloat (defValue : Float = 0F): Float = sp.getFloat(key, defValue)
163+ }
164+
165+ operator fun SharedPreferences.set (key : String , value : Any ) {
166+ when (value) {
167+ is String -> edit().putString(key, value).apply ()
168+ is Int -> edit().putInt(key, value).apply ()
169+ is Boolean -> edit().putBoolean(key, value).apply ()
170+ is Long -> edit().putLong(key, value).apply ()
171+ is Float -> edit().putFloat(key, value).apply ()
172+ }
173+ }
174+
153175}
0 commit comments