Android Spinner (Dropdown/Combobox) Tutorial (Kotlin)

June 16, 2018

Declare Spinner in XML layout.

<Spinner
    android:id="@+id/positionSpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

Load a list of string as spinner data source.

val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, listOf("None", "Top", "Bottom"))
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
positionSpinner.adapter = adapter

Listen to which item is selected.

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

    }

    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
        // either one will work as well
        // val item = parent.getItemAtPosition(position) as String
        val item = adapter.getItem(position)
    }
}

To add underline to spinner.

<Spinner
    android:id="@+id/positionSpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    style="@style/Base.Widget.AppCompat.Spinner.Underlined" />

To show item selection dropdown as fullscreen dialog.

<Spinner
    android:id="@+id/positionSpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:spinnerMode="dialog" />

References

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.