Android Key/Value Text Spinner

May 1, 2020
class SpinnerItem<T>(val id: T, val text: String? = null) {    override fun toString(): String {        return text ?: ""    }    override fun equals(other: Any?): Boolean {        if (this === other) return true        if (javaClass != other?.javaClass) return false        other as SpinnerItem<*>        if (id != other.id) return false        return true    }    override fun hashCode(): Int {        return id?.hashCode() ?: 0    }}
class Status {    companion object {        const val SUCCESS = 1        const val FAIL = -1        const val IN_PROGRESS = 0    }}

Init

val items = listOf(    SpinnerItem(Status.IN_PROGRESS, "In Progress"),    SpinnerItem(Status.SUCCESS, "Success"),    SpinnerItem(Status.FAIL, "Fail"))val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items)adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)spinner.adapter = adapter

Set Value

val value = Status.SUCCESSval position = adapter.getPosition(SpinnerItem(id = value))spinner.setSelection(position)

Listen to selected value

spinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {    override fun onNothingSelected(parent: AdapterView<*>?) {    }    override fun onItemSelected(        parent: AdapterView<*>?,        view: View?,        position: Int,        id: Long    ) {        val item = adapter.getItem(position)        val value = item.id    }}

❤️ 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.