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

前言

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

一、preference委托

class Preference<T>(val key: String, context: Context, val default: T) : ReadWriteProperty<Any?, T> {

    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 <T> preference(key: String, context: Context, default: T) = Preference(key, context, default)
}

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

四、后记

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容