zoukankan      html  css  js  c++  java
  • Kotlin偏好设置

    Kotlin的强悍震撼了我,android中每个应用都会用到SharedPreference在Kotlin中使用竟是如此简单!

    package com.android.extkt
    
    import android.content.Context
    import kotlin.properties.ReadWriteProperty
    import kotlin.reflect.KProperty
    
    /**
     * Preference
     *
     * @author 祁连山™
     * @date 2016-12-09
     * @version 1.0
     */
    
    class Preference<T>(val context: Context, val name: String, val default: T) : ReadWriteProperty<Any?, T> {
    
        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 <U> 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 <U> 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.kotlin
    
    import android.content.Intent
    import android.os.Bundle
    import android.support.v7.app.AppCompatActivity
    import com.android.extkt.Preference
    import rx.Observable
    import rx.android.schedulers.AndroidSchedulers
    import rx.schedulers.Schedulers
    import java.util.concurrent.TimeUnit
    
    class 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<in R, T> {
        
        public operator fun getValue(thisRef: R, property: KProperty<*>): T
    
        public operator fun setValue(thisRef: R, property: KProperty<*>, value: T)
    }


    -------------------------------------------------------------我是分隔线-------------------------------------------------------------

          最近项目已经使用kt来完成,用到这里时,需要清除全部缓存数据,不好一个个赋值清除,Preference有clear()却没法用,这时就需要对Preference这个代理类进行改造,也没什么可多说的,只是因为上午改的时候写错了,发现没法使用,下午单独写个demo时才发现,分享出来。

    package com.android.app

    import android.content.Context import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty
    /** * Preference * * @author 祁连山 * @date 2016-12-09 * @version 1.0 */ class Preference<T>(val context: Context) : ReadWriteProperty<Any?, T> { 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 <U> 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 <U> 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() } }


          使用方法与原来无异,只是用到Preference对象时,用主构造方法来获取,代码如下:

    ...
    var prefs = Preference(this)
    prefs.delete()
    ...
    

    代码出处:http://www.jcodecraeer.com
    代码下载:https://pan.baidu.com/s/1eR4i4ca
    其他资料:http://blog.csdn.net/TIANLANG3/article/details/53926273

  • 相关阅读:
    2014/4/9-最近所想
    DNS坑爹呢?!
    c#委托使用
    sqlserver 获取一个月有多少天
    定时提醒模型
    sqlserver导入dbf文件
    json对象中根据主键判断是否有重复数据
    差异备份与恢复
    html编码和解码
    opendatasource问题
  • 原文地址:https://www.cnblogs.com/magics/p/6148966.html
Copyright © 2011-2022 走看看