Kotlin for android學(xué)習(xí)十六(布局篇):preference委托

前言

kotlin官網(wǎng)kotlin教程學(xué)習(xí)教程的筆記。
這里使用一次委托來(lái)實(shí)現(xiàn)SharedPreferences的相關(guān)方法,用來(lái)復(fù)習(xí)一下委托O(∩_∩)O~
希望大家自己寫一遍試試,感覺(jué)不對(duì)再看對(duì)比下面的代碼,尋找原因。

一、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)

三、統(tǒng)一委托使用

我們可能不止有preference的自定義委托,可能還有其他的委托,為了方便統(tǒng)一管理,我們可以這樣。

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的教程全部結(jié)束了,anko的源碼可以多看看,很有好處的~\(≧▽≦)/~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容