Skip to content

Instantly share code, notes, and snippets.

@LexLeontiev
Created August 10, 2024 16:07
TypedListPreference
abstract class TypedListPreference<T> : ListPreference {
constructor(context: Context) : super(context)
// other common view constructors
private var defaultValue: T? = null
abstract val fromStringToType: (String) -> T?
abstract val persistType: (T) -> Boolean
abstract val getPersistedType: (T) -> T
// ListPreference calls persistString for the chosen value by default, but
// if we have a specified type and type converter, we can safely convert
// the string to the specified type and persist the value with this type
override fun persistString(value: String?): Boolean {
val typeValue = value?.let { fromStringToType(it) } ?: return false
return persistType(typeValue)
}
// To show the value in the UI, ListPreference needs to get a string.
// This is the easy part - just get the specified type and convert it
// to a string
override fun getPersistedString(defaultReturnValue: String?): String {
return defaultValue?.let {
getPersistedType(it).toString()
} ?: ""
}
// Set entry values by transforming our typed values to the String type
fun setTypedValues(typedValues: Collection<T>, defaultValue: T?) {
this.defaultValue = defaultValue
val entryValues = typedValues.map { it.toString() }.toTypedArray()
super.setEntryValues(entryValues)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment