Skip to main content

Android Spinner using Kotlin

 In this example, we’ll be implementing Material Spinners in our Android Application using Kotlin. Android Spinner is used to create a drop-down list on the screen.

What is Android Spinner?

Spinners provide a quick way to select one value from a list. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.

You can add a spinner to your layout with the Spinner object. You should usually do so in your XML layout with a <Spinner> element. For example:

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

Spinner Callback Events

 AdapterView.onItemSelectedListener interface is used to trigger the Spinner click event callbacks.
 It consists of two methods: 
 1.onItemSelected 
 2.onNothingSelected

XML Layout Code

The code for the activity_main.xml layout file is given below.


<?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"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.092" />
</androidx.constraintlayout.widget.ConstraintLayout>

Strings.xml file

create the list of the items which will be used in the dropdown menu.
 <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>


Access Spinner in MainActivity.kt file

First, we declare a variable planets-array to access the strings items from the strings.xml file.
val planetsArray = resources.getStringArray(R.array.planets_array)
then, we access the spinner and set ArrayAdaptor to control the list of items.
// Create an ArrayAdapter using the string array and a default spinner layout
val adapter = ArrayAdapter(this,
android.R.layout.simple_spinner_item, planetsArray)

// Apply the adapter to the spinner
spinner.adapter = adapter

MainActivity Kotlin Code


package com.examlpe.spinnerexample

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

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // access the items of the list
        val planetsArray = resources.getStringArray(R.array.planets_array)
        // access the spinner
        val spinner: Spinner = findViewById(R.id.spinner)

        // Create an ArrayAdapter using the string array and a default spinner layout
        val adapter = ArrayAdapter(this,
            android.R.layout.simple_spinner_dropdown_item, planetsArray)
// Apply the adapter to the spinner spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, "Selected item " + planetsArray[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // Another interface callback } } } }

Kotlin App Output

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


Comments

Post a Comment

Popular posts from this blog

Android EditText with Examples in Kotlin

In Android, EditText is a standard entry widget. A user interface element for entering and modifying text. When you define an edit text widget, you must specify the R.styleable.TextView_inputType attribute. For example, for plain text input set inputType to " text ", In case if EditText field is for password, then we need to specify the inputType as “ textPassword ”. <EditText android:id= "@+id/plain_text_input" android:layout_height= "wrap_content" android:layout_width= "match_parent" android:inputType= "text" /> See the Text Fields guide for examples of other R.styleable.TextView_inputType settings. Text Fields in Android Studio are basically EditText and we drag and drop or we can create edittext.  First, we will check the drag and drop option here EditText instance by declaring it inside a layout XML file <EditText android:id= "@+id/plain_text_input" android:layout_height= &

Lists and Grids in Android with RecyclerView Kotlin Tutorial

RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving on the efficiency of ListViews and GridViews. Getting Started To implement a basic RecyclerView Two sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice. 1.The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way. 2.The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView. Implementation of the RecyclerView: In the activity_main.xml file in layout directory, add the RecyclerView widget. <?