Android Spinner Using Kotlin With Example

In this article, we will learn about android Spinner using Kotlin. We will go through various example that demonstrates how to use different attributes of Spinner. For example, …..

In this article, we will get answer to questions like –

  • What is Spinner?
  • Why should we consider Spinner while designing ui for any app?
  • What are possibilities using Spinner while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Android Spinner Output Android Spinner Using Kotlin In Android

Tutorialwing Android Spinner Output

Getting Started

We can define android Spinner widget as below –

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

Now, how do we use Spinner in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as Spinner. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android Spinner Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using Spinner in Kotlin

Follow steps below to use Spinner in newly created project –

  • 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>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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">
    
        <Spinner
            android:id="@+id/spinner_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.spinner
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View
    import android.widget.AdapterView
    import android.widget.ArrayAdapter
    import android.widget.Spinner
    import android.widget.Toast
    import com.tutorialwing.spinner.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupSpinner()
    	}
    
    	private fun setupSpinner() {
    		val personNames = arrayOf("Rahul", "Jack", "Rajeev", "Aryan", "Rashmi", "Jaspreet", "Akbar")
    		val spinner = binding.spinnerID
    		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
    			}
    		}
    	}
    }
    

Now, run the application. We will get output as below –

Tutorialwing Android Spinner Output Android Spinner Using Kotlin In Android

Tutorialwing Android Spinner Output

Different Attributes of Spinner in XML

Now, we will see how to use different attributes of Android Spinner using Kotlin to customise it –

Set Id of Spinner

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of Spinner using android:id attribute like below –

    <Spinner
        android:id="@+id/spinner_ID"
        />

Here, we have set id of Spinner as spinner_ID using android:id=”” attribute. So, if we need to reference this Spinner, we need to use this id – spinner_ID.
Learn to Set ID of Spinner Dynamically

Set Width of Spinner

We use android:layout_width=”” attribute to set width of Spinner.
We can do it as below –

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

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of Spinner Dynamically

Set Height of Spinner

We use android:layout_height=”” attribute to set height of Spinner.
We can do it as below –

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

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of Spinner Dynamically

Set Padding of Spinner

We use android:padding=”” attribute to set padding of Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in Spinner using android:padding=”” attribute.
Learn to Set Padding of Spinner Dynamically

Set Margin of Spinner

We use android:layout_margin=”” attribute to set margin of Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in Spinner using android:layout_margin=”” attribute.
Learn to Set Margin of Spinner Dynamically

Set Background of Spinner

We use android:background=”” attribute to set background of Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in Spinner using android:background=”” attribute.
Learn to Set Background of Spinner Dynamically

Set Visibility of Spinner

We use android:visibility=”” attribute to set visibility of Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of Spinner using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of Spinner Dynamically

Set Text of Spinner

We use android:text=”” attribute to set text of Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        />

Here, we have set text (“Hello Tutorialwing”) in Spinner using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of Spinner Dynamically

Set Color of Text in Spinner

We use android:textColor=”” attribute to set color of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textColor="#ffffff"     
        />

Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in Spinner using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of Spinner Dynamically

Set Gravity of Spinner

We use android:gravity=”” attribute to set gravity of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:gravity="center_horizontal"
        />

Here, we have set gravity of text in Spinner using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of Spinner Dynamically

Set Text in Uppercase, Lowercase

If we need to show text of Spinner in uppercase or lowercase etc.

Set text in uppercase

We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textAllCaps="true"
        />

Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in Spinner.

By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textAllCaps="false"
        />

Above code will set Hello Tutorialwing to Spinner.

How do we set text in lowercase?

Answer –

  • In xml file – write all the text in lowercase.
  • In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to Spinner.

Learn to Set Text in Uppercase or Lowercase Dynamically

Set Size of Text in Spinner

We use android:textSize=”” attribute to set size of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textSize="20sp"
        />

Here, we have set size of text in Spinner using android:textSize=”” attribute.
Learn to Set Size of Text of Spinner Dynamically

Set Style (Bold/italic) of Text in Spinner

We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textStyle="bold"
        />

Here, we have set style of text in Spinner using android:textStyle=”” attribute. This attribute can take bold, italic or normal.
Learn to Set Style of Text of Spinner Dynamically

Set Letter Spacing of Text in Spinner

We use android:letterSpacing=”” attribute to set spacing between letters of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:letterSpacing="1"
        />

Here, we have set spacing between letters of text in Spinner using android:letterSpacing=”” attribute.
Learn to Set Letter Spacing of Text of Spinner Dynamically

Set Typeface of Text in Spinner

We use android:typeface=”” attribute to set typeface in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:typeface="sans"
        />

Here, we have set typeface of text in Spinner using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of Spinner Dynamically

Set fontFamily of Text in Spinner

We use android:fontFamily=”” attribute to set fontFamily of text in Spinner.
We can do it as below –

    <Spinner
        android:id="@+id/spinner_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:fontFamily="sans-serif"
        />

Here, we have set fontFamily (Here, sans-serif) of text in Spinner using android:fontFamily=”sans-serif” attribute.

Till now, we have see how to use android Spinner using Kotlin. We have also gone through different attributes of Spinner to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android Spinner Widget

Below are the various attributes that are used to customise android Spinner Widget. However, you can check the complete list of attributes of Spinner in it’s official documentation site. Here, we are going to list some of the important attributes of this 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.

We have seen different attributes of Spinner and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is Spinner, how can we use android Spinner using Kotlin ? etc. We also went through different attributes of android Spinner.