Kotlin for Android Developers
Generic preference delegate
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
26.3 Generic preference delegate
Now that we are generics experts, why not extending LongPreference to be used with any type that Shared Preferences support? Let’s create a new Preference delegate: 1 class Preference 2 : ReadWriteProperty 3 4 val prefs by lazy { 5 context.getSharedPreferences("default", Context.MODE_PRIVATE) 6 } 7 8 override fun getValue(thisRef: Any?, property: KProperty<*>): T { 9 return findPreference(name, default) 10 } 26 Settings Screen 131 11 12 override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 13 putPreference(name, value) 14 } 15 ... 16 } This preference is very similar to what we had before. We just substituted the Long references with a generic type T , and called to a couple of functions that will do the hard work. These functions are very simple, though a bit repetitive. They will check the type and use the specific method from preferences. For instance, the findPreference function looks like this: 1 private fun 2 val res: Any = when (default) { 3 is Long -> getLong(name, default) 4 is String -> getString(name, default) 5 is Int -> getInt(name, default) 6 is Boolean -> getBoolean(name, default) 7 is Float -> getFloat(name, default) 8 else -> throw IllegalArgumentException( 9 "This type can be saved into Preferences") 10 } 11 12 res as T 13 } And basically the same for putPreference function, but using the preferences editor and saving the result of when at the end, by calling apply() : 1 private fun putPreference(name: String, value: U) = with(prefs.edit()) { 2 when (value) { 3 is Long -> putLong(name, value) 4 is String -> putString(name, value) 5 is Int -> putInt(name, value) 6 is Boolean -> putBoolean(name, value) 7 is Float -> putFloat(name, value) 8 else -> throw IllegalArgumentException("This type can be saved into Pref\ 9 erences") 10 }.apply() 11 } Now update DelegatesExt object and you’re done: 26 Settings Screen 132 1 object DelegatesExt { 2 ... 3 fun preference 4 = Preference(context, name, default) 5 } After this chapter, the user can now access the settings screen and modify the zip code. That way, when they return to the main screen, the forecast will automatically be refreshed with the new information. Check the rest of small tweaks at the repository. |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling