In this tutorial, we’ll be discussing and implementing Spinners in our Android Application using Kotlin. Android Spinner is used to create a drop-down list on the screen.
What will you learn?
Spinners are like a drop-down menu that contains a list of items to select from. Once a value is selected the Spinner returns to its default state with that selected value. After Android 3.0, it’s not possible to display a prompt in a Spinner as the default state in the Spinner. Instead, the first item is displayed. Data inside a spinner is loaded with an Adapter. Take the following scenario: Imagine you need to charge your phone. For that, you must connect your phone charger to the electricity board using a pin (adapter). Then the adapter provides your phone with electricity. In Android, the Spinner is like your phone which is loaded with data using an Adapter. The adapter sets the data as well as the layout for the items to be loaded in the Spinner.
AdapterView.onItemSelectedListener
interface is used to trigger the Spinner click event callbacks. It consists of two methods:
In the following section, we’ll create a new Android Studio Project and implement Spinners in our Application. We’ll customize the layouts and learn how to handle different scenarios.
The code for the activity_main.xml layout file is given below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/linearLayout"
android:gravity="center"
tools:context=".MainActivity">
<Spinner
android:id="@+id/mySpinner"
android:layout_width="match_parent"
android:spinnerMode="dialog"
android:layout_height="wrap_content" />
</LinearLayout>
It hosts a single Spinner at the moment android:spinnerMode can be either dialog
or dropdown
.
To show prompts, you should use dialog as the spinnerMode
value.
The code for spinner_right_aligned.xml
is given below.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:padding="15dp"
android:textAlignment="gravity"
android:textColor="@color/colorPrimary"
android:textSize="16sp"
/>
The code for the MainActivity.kt class is given below.
package net.androidly.androidspinnerkotlin
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {
var languages = arrayOf("Java", "PHP", "Kotlin", "Javascript", "Python", "Swift")
val NEW_SPINNER_ID = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
with(mySpinner)
{
adapter = aa
setSelection(0, false)
onItemSelectedListener = this@MainActivity
prompt = "Select your favourite language"
gravity = Gravity.CENTER
}
val spinner = Spinner(this)
spinner.id = NEW_SPINNER_ID
val ll = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
ll.setMargins(10, 40, 10, 10)
linearLayout.addView(spinner)
aa = ArrayAdapter(this, R.layout.spinner_right_aligned, languages)
aa.setDropDownViewResource(R.layout.spinner_right_aligned)
with(spinner)
{
adapter = aa
setSelection(0, false)
onItemSelectedListener = this@MainActivity
layoutParams = ll
prompt = "Select your favourite language"
setPopupBackgroundResource(R.color.material_grey_600)
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
showToast(message = "Nothing selected")
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
when (view?.id) {
1 -> showToast(message = "Spinner 2 Position:${position} and language: ${languages[position]}")
else -> {
showToast(message = "Spinner 1 Position:${position} and language: ${languages[position]}")
}
}
}
private fun showToast(context: Context = applicationContext, message: String, duration: Int = Toast.LENGTH_LONG) {
Toast.makeText(context, message, duration).show()
}
}
Important Points:
arrayOf
strings that consist of programming languages. These are filled in the adapter using the ArrayAdapter.setDropDownViewResource
is used to set the layout for the selected state and the spinner list rows.android.R.layout.simple_spinner_item
is used to set the default android SDK layout. By default, the TextView is left aligned in this type of layout.We’ve created a second Spinner programmatically that loads the layouts from the spinner_right_aligned.xml
file.
The setSelection(0, false)
is used to prevent the Spinner’s OnItemSelected methods from firing when the Activity is created.
How does it work? The setSelection() method tells the Activity that the first spinner item was already selected. We must place this statement before onItemSelectedListener = this
. The setPopupBackgroundResource
is used to set the background color on the dropdown list. Inside the onItemSelected
function, we use the when statement to trigger a Toast for the respective Spinner item. Thanks to Kotlin and functions with default values, we’ve reduced the verbose call to the Toast.
The following is the output when the above application was run on an emulator. You can download the source code of the above project from the link below. AndroidSpinnerKotlin
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
preventing the Spinner’s OnItemSelected methods from firing when the Activity is created. this helped me alot. Thanks
- Hadi