Android spinner Using Kotlin With Example

Spinners provide a way to select one value from a list set.
In the default state, a spinner shows its currently selected value.

Create a new Project in Kotlin

  1. Open Android Studio.
  2. Go to File => New => New Project. Write application name as Spinner. Then, check Include Kotlin Support and click next button.
  3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
  4. Then, select Empty Activity => click next => click finish.
  5. You will get a newly created project successfully if you have followed steps properly.

Use the below code to Implement a Spinner with Kotlin

MainActivity.kt
package com.example.myapplicationkotlinetest

import android.support.v7.app.AppCompatActivity

import android.os.Bundle

import kotlinx.android.synthetic.main.activity_main.*

import android.view.View

import android.widget.*

import java.util.ArrayList as ArrayList1

class MainActivity : AppCompatActivity(),AdapterView.OnItemSelectedListener {
val languagesList = ArrayList()
var spinnerlanguages:Spinner? = null
var textView_languages:TextView? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    textView_languages = this.msg
    spinnerlanguages = this.spinner_sample
    languagesList.add("English")
    languagesList.add("French")
    languagesList.add("Hindi")

    spinnerlanguages!!.setOnItemSelectedListener(this)

    // Create an ArrayAdapter using a simple spinner layout and languages array
    val aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languagesList)
    // Set layout to use when the list of choices appear
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    // Set Adapter to Spinner
    spinnerlanguages!!.setAdapter(aa)

}

override fun onItemSelected(arg0: AdapterView<*>, arg1: View, position: Int, id: Long) {
    textView_languages!!.text = "Selected language: "+languagesList[position]
}

override fun onNothingSelected(arg0: AdapterView<*>) {

}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical   " 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<TextView
        android:id="@+id/msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:padding="20dp"/>

<Spinner
        android:id="@+id/spinner_sample"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
        
</LinearLayout>