最近中文字幕高清中文字幕无,亚洲欧美高清一区二区三区,一本色道无码道dvd在线观看 ,一个人看的www免费高清中文字幕

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

Kotlin對(duì)SP使用的封裝

標(biāo)簽:
Kotlin

为了更易于使用SharedPreferences,使用Koltin的委托模式来对SP进行封装

1. 定义委托类

class Preference<T>(val name: String, val default: T) {    val prefs: SharedPreferences by lazy { MyApp.instance.applicationContext.getSharedPreferences("SP", Context.MODE_PRIVATE) }    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = getSharedPreferences(name, default)    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = putSharedPreferences(name, value)    private fun putSharedPreferences(name: String, value: T) = with(prefs.edit()) {        when(value) {            is Int -> putInt(name, value)            is Float -> putFloat(name, value)            is Long -> putLong(name, value)            is Boolean -> putBoolean(name, value)            is String -> putString(name, value)            else -> throw IllegalArgumentException("SharedPreference can't be save this type")
        }.apply()
    }    private fun getSharedPreferences(name:String, default: T): T = with(prefs) {        val res: Any = when(default) {            is Int -> getInt(name, default)            is Float -> getFloat(name, default)            is Long -> getLong(name, default)            is Boolean -> getBoolean(name, default)            is String -> getString(name, default)            else -> throw IllegalArgumentException("SharedPreference can't be get this type")
        }        return res as T
    }
}

2. 定义使用的静态方法

object DelegatesExt {    fun <T> preference(name: String, default: T) = Preference(name, default)
}

3.简单使用

var mGuideEnable by DelegatesExt.preference("guide", false)



作者:kermitye
链接:https://www.jianshu.com/p/861c17162039


點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消