Android Spinner Using Kotlin With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners

Hello Readers! In this post, we are going to learn how to use android spinner using kotlin in any android application. We will also learn about different attributes of android spinner that can be used to customize spinner widget in any android application.

Output

Tutorialwing Android Spinner Output Android Spinner Using Kotlin In Android

Tutorialwing Android Spinner Output

Getting Started

Android Spinner widget can be defined as below –

Android spinner is a widget that have multiple options as list in the dropdown, but finally shows option selected by the user.

Note – Options in the dropdown are provided by the adapter. We must provide an adapter to the spinner.

Different Attributes of Android Spinner Widget

Some of the popular attributes of android spinner widget are –

Sr. XML Attributes Description
1 android:dropDownHorizontalOffset This is used to set horizontal offset of the dropdown shown in spinner.
2 android:dropDownSelector This is used as list selector when spinnerMode is dropdown.
3 android:dropDownVerticalOffset This is used to set vertical offset of the dropdown shown in spinner.
4 android:dropDownWidth This is used to set width of the dropdown when spinnerMode=”dropdown”
5 android:gravity It specifies the position of the currently selected item.
6 android:popupBackground Sets background of the dropdown when spinnerMode=”dropdown”
7 android:prompt Prompt to show when the spinner’s dialog is shown.
8 android:spinnerMode Sets the display mode for spinner options.

Attributes of spinner widget are also inherited from AbsSpinner, ViewGroup and View. Some of the popular attributes of android spinner inherited from AbsSpinner are –

Sr. XML Attributes Description
1 android:entries This is used to set reference to an array resource that will populate the spinner.

Some of the popular attributes of android spinner inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:addStatesFromChildren It is used to set whether viewgroup’s drawable state also include it’s children drawable states.
2 android:alwaysDrawnWithCache It is used to set whether viewgroup’s children will be drawn using their drawable cache or not.
3 android:animateLayoutChanges It defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run.
4 android:animationCache It is used to set whether layout animations should create a drawing cache for their children.
5 android:clipChildren It is used to set whether a child is limited to draw inside of its bounds or not.

Some of the popular attributes of android spinner inherited from View are –

Sr. XML Attributes Description
1 android:alpha Specifies alpha of the view.
2 android:background Specifies background drawable of the view.
3 android:clickable Specifies whether view is clickable or not.
4 android:elevation Specifies base z-depth of the view.
5 android:id Specifies unique id of the view. Note – Id of the view must always be unique in an xml file.
6 android:padding Specifies padding of the view.
7 android:textAlignment Specifies alignment of the text.
8 android:visibility Specifies visibility(VISIBLE, INVISIBLE etc.) of the view.



Example of Android Spinner Using Kotlin

At first, we will create an android application. Then, we will create and use android spinner using kotlin in this application.

1. Creating New Project in Kotlin

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
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.

Since we have a project now, we will modify xml and kotlin file to use android spinner using kotlin in the project.

2. Modify values folder

Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">Spinner</string>
	<string name="selected_item">Selected item:</string>
</resources>

Now, we will use spinner widget in the xml file.

3. Use Spinner Widget in xml file

Open src/main/res/layout/activity_main.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@android:color/white"
	android:gravity="center">

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

</LinearLayout>

in activity_main.xml file, we have defined a spinner widget. Now, we will access this spinner in kotlin file. Then, we will set a listener to show toast message whenever a new item is selected in spinner.

4. Access Android Spinner Widget in Kotlin file

Open src/main/java/com.tutorialwing.spinner/MainActivity.kt file and add below code into it.

package com.tutorialwing.spinner

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast

class MainActivity : AppCompatActivity() {

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

        val personNames = arrayOf("Rahul", "Jack", "Rajeev", "Aryan", "Rashmi", "Jaspreet", "Akbar")
        val spinner = findViewById<Spinner>(R.id.spinner)
        if (spinner != null) {
            val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personNames)
            spinner.adapter = arrayAdapter

            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                    Toast.makeText(this@MainActivity, getString(R.string.selected_item) + " " + personNames[position], Toast.LENGTH_SHORT).show()
                }

                override fun onNothingSelected(parent: AdapterView<*>) {
                    // Code to perform some action when nothing is selected
                }
            }
        }
    }
}

In MainActivity.kt file, we have accessed spinner widget, defined in xml file. Then, we created an adapter for spinner widget. Then, we have set this adapter to spinner. At last, we have set a listener to show toast message whenever a new item is selected from dropdown menu of spinner widget.

Since AndroidManifest.xml file is very important in any android application, we are also going through the code inside this manifest file.

AndroidManifest.xml file

Code inside main/AndroidManifest.xml file is as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.spinner"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

When we run the program, we will get output as shown above.

That’s end of our tutorial on Android Spinner using Kotlin.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners