Kotlin for android学习十六(布局篇):preference委托

前言

kotlin官网和kotlin教程学习教程的笔记。
这里使用一次委托来实现SharedPreferences的相关方法,用来复习一下委托O(∩_∩)O~
希望大家自己写一遍试试,感觉不对再看对比下面的代码,寻找原因。

一、preference委托

class Preference(val key: String, context: Context, val default: T) : ReadWriteProperty {

    val prefs by lazy { context.getSharedPreferences("file", Context.MODE_PRIVATE) }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(key, value)
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return findPreference(key, default)
    }

    private fun findPreference(key: String, default: T) = with(prefs) {
        val result: Any = when (default) {
            is String -> getString(key, default)
            is Int -> getInt(key, default)
            else -> throw IllegalArgumentException("this type can not be readed")
        }
        result as T
    }

    private fun putPreference(key: String, value: T) = with(prefs.edit()) {
        when (value) {
            is String -> putString(key, value)
            is Int -> putInt(key, value)
            else -> throw IllegalArgumentException("this type can not be saved")
        }
    }.commit()
}

二、使用

  var id: Int by Preference(ID, this, 0)

三、统一委托使用

我们可能不止有preference的自定义委托,可能还有其他的委托,为了方便统一管理,我们可以这样。

object CustomDelegate{
    fun  preference(key: String, context: Context, default: T) = Preference(key, context, default)
}

var id: Int by CustomDelegate.preference(ID, this, 0)

四、后记

至此,kotlin的教程全部结束了,anko的源码可以多看看,很有好处的~\(≧▽≦)/~

你可能感兴趣的:(Kotlin for android学习十六(布局篇):preference委托)