Kotlin的强悍震撼了我,android中每个应用都会用到SharedPreference在Kotlin中使用竟是如此简单!
package com.android.extktimport android.content.Contextimport kotlin.properties.ReadWritePropertyimport kotlin.reflect.KProperty/** * Preference * * @author 祁连山™ * @date 2016-12-09 * @version 1.0 */class Preference(val context: Context, val name: String, val default: T) : ReadWriteProperty { val prefs by lazy { context.getSharedPreferences("default", Context.MODE_PRIVATE) } override fun getValue(thisRef: Any?, property: KProperty<*>): T { return findPreference(name, default) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { putPreference(name, value) } private fun findPreference(name: String, default: U): U = 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 not be saved") } res as U } private fun putPreference(name: String, value: U) = 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 not be saved") }.apply() }}
使用时直接读取赋值,再也不用edit、commit,以我们最常用的引导页判断来说,如果是第一次进入应用跳转到GuideActivity,否则启动MainActivity,使用Kotlin码出来就是下面这个样子:
package com.android.kotlinimport android.content.Intentimport android.os.Bundleimport android.support.v7.app.AppCompatActivityimport com.android.extkt.Preferenceimport rx.Observableimport rx.android.schedulers.AndroidSchedulersimport rx.schedulers.Schedulersimport java.util.concurrent.TimeUnitclass SplashActivity : AppCompatActivity() { private var first: Boolean by Preference(this, "first", true) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) val observable = Observable.timer(3000, TimeUnit.MILLISECONDS) observable.observeOn(AndroidSchedulers.mainThread()) observable.subscribeOn(Schedulers.io()) observable.subscribe({ route() }) } override fun onBackPressed() { return } fun route(): Unit { var intent = Intent() if (first) { intent.setClass(this, GuideActivity::class.java) startActivity(intent) // 可以在这里直接存储first的值 // first = false this.finish() return } intent.setClass(this, MainActivity::class.java) startActivity(intent) this.finish() }}
在Kotlin中,声明成员属性,除了直接赋值,还可以用 Delegate 的方式来声明,这个 Delegate 需要根据成员的类型(val 或者 var)来提供相应的 getValue 和 setValue 方法,比如一个可读写的 Delegate,需要提供下面的方法:
public interface ReadWriteProperty{ public operator fun getValue(thisRef: R, property: KProperty<*>): T public operator fun setValue(thisRef: R, property: KProperty<*>, value: T)}
package com.android.app import android.content.Contextimport kotlin.properties.ReadWritePropertyimport kotlin.reflect.KProperty/** * Preference * * @author 祁连山 * @date 2016-12-09 * @version 1.0 */class Preference(val context: Context) : ReadWriteProperty { var key: String? = null var value: T? = null constructor(context: Context, name: String, default: T) : this(context) { key = name value = default } val prefs by lazy { context.getSharedPreferences("default", Context.MODE_PRIVATE) } override fun getValue(thisRef: Any?, property: KProperty<*>): T { return findPreference(key!!, value!!) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { putPreference(key!!, value) } fun delete(vararg key: String): Unit { if (key.size == 0) { prefs.edit().clear().commit() return } for (i in 0..key.size) { prefs.edit().remove(key[i]).commit() } } private fun findPreference(name: String, default: U): U = 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("The data can not be saved") } res as U } private fun putPreference(name: String, value: U) = 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("The data can not be saved") }.apply() }}
...var prefs = Preference(this)prefs.delete()...
代码出处:
代码下载:其他资料: