0
以下代码是关于Kotlin的示例项目,我可以使用Code 1来获取共享首选项的值,但是我可以设置共享首选项的值?如何在Kotlin中设置值首选项?
我无法在示例项目中找到这些代码,您能告诉我我该怎么办?谢谢!
代码1
class SettingsActivity : AppCompatActivity() {
companion object {
val ZIP_CODE = "zipCode"
val DEFAULT_ZIP = 94043L
}
var zipCode: Long by DelegatesExt.preference(this, ZIP_CODE, DEFAULT_ZIP)
}
代码2
object DelegatesExt {
fun <T> notNullSingleValue() = NotNullSingleValueVar<T>()
fun <T> preference(context: Context, name: String, default: T) = Preference(context, name, default)
}
class NotNullSingleValueVar<T> {
private var value: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = if (this.value == null) value
else throw IllegalStateException("${property.name} already initialized")
}
}
class Preference<T>(val context: Context, val name: String, val default: T) {
val prefs: SharedPreferences by lazy { context.getSharedPreferences("default", Context.MODE_PRIVATE) }
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreference(name, default)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreference(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("This type can be saved into Preferences")
}
res as T
}
private fun putPreference(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("This type can't be saved into Preferences")
}.apply()
}
}
和更多
如果函数putPreference是公共的,我可以使用设置的共享偏好的值下面的代码,但它的丑陋
class SettingsActivity : AppCompatActivity() {
companion object {
val ZIP_CODE = "zipCode"
val DEFAULT_ZIP = 94043L
}
DelegatesExt.Preference(this, ZIP_CODE, DEFAULT_ZIP).putPreference(ZIP_CODE,"99999L");
}
谢谢!你能写一个完整的代码来设置共享首选项的值吗?我不明白为什么'activity.zipCode =“MyNewZIP”'将调用setValue(activity,“zipCode”,...)' – HelloCW
因为这就是委派属性如何定义的工作。你有没有读过链接? –
您不能使用'“MyNewZIP”',因为类型是“Long”(这对于邮政编码来说并不合适)。 –