美文网首页
kotlin 属性代理 代理SharedPreference

kotlin 属性代理 代理SharedPreference

作者: 菜鸟何时起飞 | 来源:发表于2020-08-26 11:59 被阅读0次
class Preference<T>(val context: Context, val name: String, val default: T, val prefName: String = "default") : ReadWriteProperty<Any?, T> { 
   
     constructor(context: Context, default: T, prefName: String = "default"): this(context, "", default, prefName) 
   
     val prefs by lazy { context.getSharedPreferences(prefName, Context.MODE_PRIVATE) } 
   
     override fun getValue(thisRef: Any?, property: KProperty<*>): T { 
         return findPreference(findProperName(property), default) 
     } 
   
     override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 
         putPreference(findProperName(property), value) 
     } 
   
     private fun findProperName(property: KProperty<*>) = if(name.isEmpty()) property.name else name 
   
     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("Unsupported type") 
         } 
   
         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("Unsupported type") 
         }.apply() 
     } 
 } 

相关文章

网友评论

      本文标题:kotlin 属性代理 代理SharedPreference

      本文链接:https://www.haomeiwen.com/subject/cxmxsktx.html