Android Spinner with Example in Kotlin

Android Spinner provides an option set, where user can select any one of option. Like a list of city, in this case, a user can select on the city. The advantage of Spinner is giving more option list in less space.

The Default state of the spinner is shown currently selected value. User has to touch the spinner to show the dropdown list of all available values and then touch (click) any one of value.

Android Spinner with Example in Kotlin

In this tutorial, you will learn following:

  1. Add a Spinner in XML resource layout file , and load the selection items via XML “values/strings” file also.
  2. Add another Spinner in XML and load the selection items via code programmatically  (dynamically).
  3. Get the value of selected spinners items, on click button

You can set values in spinner in 2 ways:

First by using “android:entries” attributes in spinner widget.

Second, using ArrayAdapter, In both case we will use resource values string-array.

Let’s Build a Simple Example of Android Spinner :

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. Add string array resources in xml

Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).

File : res/values/strings.xml

Step 3. Add below code in “activity_main.xml” resource file

add 2 Spinners in the resource file and add id to both ,one spinner will have onClick attribute to call actions on user touch.

Step 4. Open the “MainActivity.kt” and add following code

call getValues function to get values of spinner and show in Toast message.

Step 5. Now Run the application, in emulator or On you android device

Output screenshot Android Spinner example :

Android Spinner with Example in Kotlin output

Download source code Android Spinner in kotlin

https://github.com/EyeHunts/AndroidSpinner

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 27: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”27″

Coding in Kotlin


One thought on “Android Spinner with Example in Kotlin

  1. Android Studio indicates that ‘spinner’ on line 23 is an ‘Unresolved reference: spinner.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.