How should I use an ArrayMap<String, CustomClass> to be the data source for a Spinner in Android? I would like it to use the .name field of the CustomClass as label in the Spinner. The map is dynamic as it contains devices that are detected.
How should I use an ArrayMap<String, CustomClass> to be the data source for a Spinner in Android? I would like it to use the .name field of the CustomClass as label in the Spinner. The map is dynamic as it contains devices that are detected.
Usually for Spinners, Map types are not recommended for creating array adapter. Because maps does not maintain order. So for example if you need do something based on position , it might not work as intended.
If you definitely need to use ArrayMap , here is the code to do that. You need to convert values of map values toList and pass it to adapter. And to control the text, you need to override toString method for custom class, which will be the data shown in spinner.
class Foo constructor(var foo: String,var bar:String){
override fun toString(): String {
return "$foo:$bar"
}
}
val arrayMap = ArrayMap<String,Foo>()
arrayMap["cde"] = Foo("Some","Content")
arrayMap["abc"] = Foo("Hello","World")
val dataAdapter2 = ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayMap.values.toList())
In spinner it will show like below,
Hello:World
Some:Content