Android Spinner using Kotlin

Filed Under: Android

In this tutorial, we’ll be discussing and implementing Spinners in our Android Application using Kotlin. Android Spinner is used to create a drop-down list on the screen.

What will you learn?

  • Creating Spinners through XML and Programmatically
  • Setting a prompt on the Spinner.
  • Creating a custom layout for the Spinner.
  • Handling Click Listeners and Display a Toast message.
  • Preventing the Click Listener from being fired automatically for the first time.

What is Android Spinner?

Spinners are like a drop-down menu that contains a list of items to select from. Once a value is selected the Spinner returns to its default state with that selected value.

After Android 3.0, it’s not possible to display a prompt in a Spinner as the default state in the Spinner. Instead, the first item is displayed.

Data inside a spinner is loaded with an Adapter.

Take the following scenario:

Imagine you need to charge your phone. For that, you must connect your phone charger to the electricity board using a pin (adapter). Then the adapter provides your phone with electricity. In Android, the Spinner is like your phone which is loaded with data using an Adapter. The adapter sets the data as well as the layout for the items to be loaded in the Spinner.

Spinner Callback Events

AdapterView.onItemSelectedListener interface is used to trigger the Spinner click event callbacks.

It consists of two methods:

  • onItemSelected
  • onNothingSelected

In the following section, we’ll create a new Android Studio Project and implement Spinners in our Application. We’ll customize the layouts and learn how to handle different scenarios.

Android Spinner Kotlin Project

android spinner kotlin

1. XML Layout Code

The code for the activity_main.xml layout file is given below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/linearLayout"
    android:gravity="center"
    tools:context=".MainActivity">

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

</LinearLayout>

It hosts a single Spinner at the moment android:spinnerMode can be either dialog or dropdown.

To show prompts, you should use dialog as the spinnerMode value.

2. Spinner XML Code

The code for spinner_right_aligned.xml is given below.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="end"
    android:padding="15dp"
    android:textAlignment="gravity"
    android:textColor="@color/colorPrimary"
    android:textSize="16sp"
    />

3. MainActivity Kotlin Code

The code for the MainActivity.kt class is given below.

package net.androidly.androidspinnerkotlin

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {


    var languages = arrayOf("Java", "PHP", "Kotlin", "Javascript", "Python", "Swift")
    val NEW_SPINNER_ID = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        var aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        with(mySpinner)
        {
            adapter = aa
            setSelection(0, false)
            onItemSelectedListener = this@MainActivity
            prompt = "Select your favourite language"
            gravity = Gravity.CENTER

        }

        val spinner = Spinner(this)
        spinner.id = NEW_SPINNER_ID

        val ll = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

        ll.setMargins(10, 40, 10, 10)
        linearLayout.addView(spinner)

        aa = ArrayAdapter(this, R.layout.spinner_right_aligned, languages)
        aa.setDropDownViewResource(R.layout.spinner_right_aligned)

        with(spinner)
        {
            adapter = aa
            setSelection(0, false)
            onItemSelectedListener = this@MainActivity
            layoutParams = ll
            prompt = "Select your favourite language"
            setPopupBackgroundResource(R.color.material_grey_600)

        }

    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
        showToast(message = "Nothing selected")
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

        when (view?.id) {
            1 -> showToast(message = "Spinner 2 Position:${position} and language: ${languages[position]}")
            else -> {
                showToast(message = "Spinner 1 Position:${position} and language: ${languages[position]}")
            }
        }
    }

    private fun showToast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_LONG) {
        Toast.makeText(context, message, duration).show()
    }
}

Important Points:

  • Thanks to Kotlin Android extensions, the XML Spinner widget is automatically available in our Kotlin Activity class.
  • We’ve created an arrayOf strings that consist of programming languages. These are filled in the adapter using the ArrayAdapter.
  • The setDropDownViewResource is used to set the layout for the selected state and the spinner list rows.
  • The android.R.layout.simple_spinner_item is used to set the default android SDK layout. By default, the TextView is left aligned in this type of layout.

We’ve created a second Spinner programmatically that loads the layouts from the spinner_right_aligned.xml file.

The setSelection(0, false) is used to prevent the Spinner’s OnItemSelected methods from firing when the Activity is created.

How does it work?
The setSelection() method tells the Activity that the first spinner item was already selected. We must place this statement before onItemSelectedListener = this.

The setPopupBackgroundResource is used to set the background color on the dropdown list.

Inside the onItemSelected function, we use the when statement to trigger a Toast for the respective Spinner item.

Thanks to Kotlin and functions with default values, we’ve reduced the verbose call to the Toast.

4. Spinner Kotlin App Output

The following is the output when the above application was run on an emulator.
android spinner kotlin output

You can download the source code of the above project from the link below.
AndroidSpinnerKotlin

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages