Android Spinner With Key Value Object Adapter (Kotlin)

June 17, 2018

NOTE: Refer to Android Spinner (Dropdown/Combobox) Tutorial (Kotlin).

Create a class for the Key Value object.

class EnumTextItem<T>(val id: T, val text: String) {
    override fun toString(): String {
        return text
    }
}

I created enum to for the id/key.

enum class Position {
    TOP, BOTTOM
}

Create adapter for spinner.

val positionAdapter = ArrayAdapter<EnumTextItem<Position>>(context, android.R.layout.simple_spinner_item, listOf(EnumTextItem(Position.BOTTOM, "Bottom"), EnumTextItem(Position.TOP, "Top"))).also { adapter ->
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    positionSpinner.adapter = adapter
}

Handle item selected event.

positionSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onNothingSelected(parent: AdapterView<*>?) {

    }

    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
        // val item = parent.getItemAtPosition(position) as EnumTextItem<Position>
        val item = positionAdapter.getItem(position)

        if (item.id == Position.BOTTOM) {
            // ...
        }
        else if (item.id == Position.BOTTOM) {
            // ...
        }
    }
}        
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.