Kotlin Android Spinner - Fill From Array and ItemSelectionListener

Kotlin Array

This is a tutorial for population of spinner from a Kotlin Array and handling the spinner's itemSelection event.

Spinner is a widget, of course defined in the android.widget package and allows us render items in a dropdwon fashion.

In this tutorial we want to see how to set array of items in our spinner. Our programming language is Kotlin.

We also see how to retrieve the selected item and display them in a Toast.

Let's go.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel.

Basically we have a TV for programming where do daily tutorials especially android.

Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.

Android Spinner

Spinner is an AdapterView. This means that it relies on an Adapter for its data.

Adapters act as the bridge between adapterviews and the underlying data source.

This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.

Spinner is a concrete public class residing in the android.widget package.

package android.widget;

Spinner is a public class that's why we can access and use it.

public class Spinner{}

Public classes are visible even from other packages apart from those they've been defined.

Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.

AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.

Kotlin Simple Spinner Example

Here's our example.

Kotlin Android Spinner Array

Let's write some code.

Resoources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let's start by looking at the layout resources

(a). activity_main.xml

This layout will get inflated into the main activity's user interface. This will happen via the Activity's setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

In our case we will make use of the following widgets and viewgroups:

  1. LinearLayout - Will arrange our TextView and Spinner linearly with TextView on top of Spinner.
  2. TextView - Will display the header text of our app.
  3. Spinner - Will render our data in dropdown fashion.

Here's the code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="info.camposha.kotlinspinner.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Nebulas App"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorAccent" />

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

</LinearLayout>

Kotlin Code.

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Kotlin programming language.

We will have these classes in our project.

(a)MainActivity.kt

This is our launcher activity as the name suggests. This means it will be the main entry point to our app in that when the user clicks the icon for our app, this activity will get rendered first.

We override a method called onCreate(). Here we will start by inflating our main layout via the setContentView() method.

Our main activity is actually an activity since it's deriving from the AppCompatActivity.

package info.camposha.kotlinspinner

import android.support.v7.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)

        val nebulae = arrayOf<String>("Boomerang", "Orion", "Witch Head", "Ghost Head", "Black Widow", "Flame", "Cone","Pelican","Helix","Snake","Elephant's Trunk")

        val mySpinner = findViewById(R.id.mySpinner) as Spinner

        var adapter= ArrayAdapter(this,android.R.layout.simple_list_item_1,nebulae)
        mySpinner.adapter=adapter

        //LISTENER
        mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
                Toast.makeText([email protected], nebulae[i], Toast.LENGTH_SHORT).show()
            }
            override fun onNothingSelected(adapterView: AdapterView<*>) {
            }
        }
    }
}

Best regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post