Tutorials  /  JavaScript

Android Spinner: Effective Implementation with Kotlin

Ccentron Redaktion · September 2024 ·4 min read ·JavaScript, Tutorial

Platzhalter Text

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
VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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:

Code
<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:

Code
<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:

Go
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!

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren