Skip to content

Commit 8feddce

Browse files
committed
AndroidExtensions: SharedPreferences getter & setter
Signed-off-by: Fung <fython@163.com>
1 parent 4eb292a commit 8feddce

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

kotlinyan-common/src/main/kotlin/moe/feng/kotlinyan/common/AndroidExtensions.kt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package moe.feng.kotlinyan.common
22

33
import android.annotation.SuppressLint
44
import android.content.Intent
5+
import android.content.SharedPreferences
56
import android.os.Build
67
import android.os.Bundle
78
import 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

Comments
 (0)