Create a Spinner in android using Kotlin, spinner on item selected listener android, spinner android example,   spinner in kotlin,

Create a Spinner in android using Kotlin

A spinner in android is basically a dropdown list with items filled on it and allows users to choose from the defined list. When we compare a spinner in android with web development, it is simply the same as the select element with items added as options

The spinner allows the user to select one item at a time and it is mostly preferred to other elements since if you have a list with a large number of items, they can be defined in a spinner and will be presented or displayed without occupying the whole page as opposed to the list view.

In this article, we shall focus on how to create a spinner in android using kotlin language, add a click listener to the spinner such that when you select an item, you can get its position and its name.

To understand how a spinner works, we shall use an example whereby we will display the most common car models in a spinner.

To begin creating a spinner in android using kotlin, you will need to set up your project first.

  • In the xml file, add the spinner element which will be used to hold the items that are defined in a list as follows

<Spinner

            android:id="@+id/spinner"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            tools:ignore="MissingConstraints" />

  • Once you select an item from the spinner list, the name of the item selected will be displayed in a text view and also a toast. Below the spinner add the text view element

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text=""

        android:id="@+id/textview"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

The full activity_main.xml code will be as below

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

 

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:orientation="vertical"

        android:paddingTop="100dp"

        android:paddingLeft="100dp"

        tools:ignore="MissingConstraints">

 

        <Spinner

            android:id="@+id/spinner"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            tools:ignore="MissingConstraints" />

 

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text=""

        android:id="@+id/textview"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

  • In the kotlin file named MainActivity.kt, you will need to import the adapters and views that are used for all the items defined, that is, the spinner, textview, toast, array adapter and array view as shown

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.view.View

import android.widget.Toast

import android.widget.Spinner

import android.widget.TextView

import android.widget.ArrayAdapter

import android.widget.AdapterView

  • Define the items which you want to be shown in the spinner as an array. In this example we are using the car models

var carmodels = arrayOf("Mercedez Benz", "Volvo", "Volkswagen", "Nissan", "Toyota", "Honda", "KIA", "Mitsubishi", "Subaru", "Suzuki")

  • Instantiate the text view and spinner in the main activity by calling them from the xml file

var spinner: Spinner? = null

var textview: TextView? = null

 

 textview = findViewById(R.id.textview) as TextView

 spinner = findViewById(R.id.spinner) as Spinner

  • Create an adapter and add the array values to the adapter by defining a sample layout as shown

// Create an ArrayAdapter using a simple spinner layout and car models array

        val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, carmodels)

        // Set layout to use when the spinner with the list is displayed

        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        // Set Adapter to Spinner

        spinner!!.setAdapter(arrayAdapter)

So far when you build and run the app, the array list values will be added to the spinner and will be displayed meaning you have already known how to create a spinner in android using kotlin

Next, we will now focus on how to select an item from the spinner and note its value

On item selected listener from a spinner

We use the on item selected listener method where we create two classes one for when an item is selected and when nothing is selected.

When an item is selected, we display the name of the item selected in a text view and also in a toast.

When no item is selected, no action is taken

Remember, by default, the first item on the list act as a selected item in the spinner meaning when you open the app, the first item will behave as if it has been selected or clicked

spinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(

                parent: AdapterView<*>?,

                view: View?,

                position: Int,

                id: Long

            ) {

                Toast.makeText(this@MainActivity, carmodels[position], Toast.LENGTH_LONG)

                    .show()

                textview!!.text = "The selected car model is : " + carmodels[position]

            }

 

            override fun onNothingSelected(parent: AdapterView<*>?) {

                //no activity or action when nothing is selected

            }

        }

The full code for main activity kotlin file is as below

package com.example.spinnerexample

 

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.view.View

import android.widget.Toast

import android.widget.Spinner

import android.widget.TextView

import android.widget.ArrayAdapter

import android.widget.AdapterView

 

class MainActivity : AppCompatActivity() {

 

    var carmodels = arrayOf("Mercedez Benz", "Volvo", "Volkswagen", "Nissan", "Toyota", "Honda", "KIA", "Mitsubishi", "Subaru", "Suzuki")

 

    var spinner: Spinner? = null

    var textview: TextView? = null

 

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

 

        textview = findViewById(R.id.textview) as TextView

 

         spinner = findViewById(R.id.spinner) as Spinner

 

        // Create an ArrayAdapter using a simple spinner layout and car models array

        val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, carmodels)

        // Set layout to use when the spinner with the list is displayed

        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        // Set Adapter to Spinner

        spinner!!.setAdapter(arrayAdapter)

 

        spinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(

                parent: AdapterView<*>?,

                view: View?,

                position: Int,

                id: Long

            ) {

                Toast.makeText(this@MainActivity, carmodels[position], Toast.LENGTH_LONG)

                    .show()

                textview!!.text = "The selected car model is : " + carmodels[position]

            }

 

            override fun onNothingSelected(parent: AdapterView<*>?) {

                //no activity or action when nothing is selected

            }

        }

 

    }

 

}

 

That is how we create a spinner in android using kotlin and also how we act when an item is selected from the spinner list. Hope you have followed keenly and learned how to work with spinner in android