Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Platzhalter Text

Android Spinner: Effective Implementation with Kotlin

Dive into the fascinating world of Android Spinners with Kotlin! Our hands-on tutorial guides you through creating dropdown menus, customizing layouts, and handling click events. With step-by-step instructions and helpful tips, you’ll be ready to take your Android apps to the next level.

What will you learn?

  • Creating spinners via XML and programmatically
  • Setting up a placeholder on the spinner
  • Creating a custom layout for the spinner
  • Handling click events and displaying a toast message
  • Preventing the click event from being triggered automatically the first time

What is an Android Spinner?

Spinners are like a dropdown menu containing a list of items to choose from. Once a value is selected, the spinner returns to its default state with that selected value. Since Android 3.0, it’s no longer possible to display a placeholder in a spinner as the default state. Instead, the first element is shown. Data within a spinner is loaded using an adapter.

Spinner Callback Events

The AdapterView.onItemSelectedListener interface is used to trigger spinner click event callbacks. It consists of two methods:

  • onItemSelected
  • onNothingSelected

In the following section, we’ll create a new Android Studio project and implement spinners in our application, customizing layouts and learning how to handle different scenarios.

Android Spinner Kotlin Project

1. XML Layout Code

The code for the activity_main.xml layout file looks like this:

<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 currently hosts a single spinner. android:spinnerMode can be either dialog or dropdown. To display placeholders, dialog should be used as the value for spinnerMode.

2. Spinner XML Code

The code for spinner_right_aligned.xml is as follows:

<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" />

3. MainActivity Kotlin Code

The code for the MainActivity.kt class looks like this:

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 = "Choose your favorite 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 = "Choose your favorite 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()
    }
}

Key points:

  • Thanks to Kotlin Android Extensions, the XML spinner widget is automatically available in our Kotlin activity class.
  • We have created an array of strings containing programming languages, which are filled in the adapter with ArrayAdapter.
  • setDropDownViewResource is used to set the layout for the selected state and the spinner list items.
  • android.R.layout.simple_spinner_item is used to set the default Android SDK layout. By default, the TextView in this layout is left-aligned.
  • We programmatically created a second spinner that loads layouts from the spinner_right_aligned.xml file.
  • setSelection(0, false) is used to prevent the OnItemSelected methods of the spinner from being triggered when the activity is created.

How does it work?

The setSelection() method informs the activity that the first spinner element has already been selected. We need to place this instruction before onItemSelectedListener = this. 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 message for the corresponding spinner element. Thanks to Kotlin and functions with default values, we have reduced the cumbersome call of the toast.

4. Spinner Kotlin App Output

The following image shows the output when the above application is run on an emulator.

Ready to spice up your Android apps with spinners? Have fun coding with Kotlin!

Experience the Power of Cloud Development Today!

Ready to elevate your Android app development with seamless cloud integration? Start your free trial of our cloud services now and unlock the full potential of your Kotlin projects. With our platform, you'll enjoy enhanced performance, scalability, and effortless management. Don't miss out on this opportunity—sign up today and take the next step in your development journey!

Try for free!