Android Spinner (Dropdown/Combobox) Tutorial (Kotlin)

Jun 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

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