I had made some extension function of Spinner for loading data and tracking item selection.
Spinner.kt
fun <T> Spinner.load(context: Context, items: List<T>, item: T? = null) { adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } if (item != null && items.isNotEmpty()) setSelection(items.indexOf(item)) } inline fun Spinner.onItemSelected( crossinline itemSelected: ( parent: AdapterView<*>, view: View, position: Int, id: Long ) -> Unit ) { onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { itemSelected.invoke(parent, view, position, id) } } }
Usaage Example
val list = listOf("String 1", "String 2", "String 3") val defaultData = "String 2" // load data to spinner your_spinner.load(context, list, defaultData) // load data without default selection, it points to first item your_spinner.load(context, list) // for watching item selection your_spinner.onItemSelected { parent, view, position, id -> // do on item selection }
spinner.setSelection(). That would work just fine. You can also create a method that can help you match your indexes to their actual strings.