Android Spinner With Key Value Object Adapter (Kotlin)

Jun 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) {            // ...        }    }}        

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.