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.SUCCESS

val 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
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.