Access Spinner in MainActivity.kt file
First, we declare a variable languages to access the strings items from the strings.xml file.
val languages = resources.getStringArray(R.array.Languages)
then, we access the spinner and set ArrayAdaptor to control the list of items.
val spinner = findViewById(R.id.spinner) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter
Kotlin
package com.w3wiki.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the items of the list val languages = resources.getStringArray(R.array.Languages) // access the spinner val spinner = findViewById<Spinner>(R.id.spinner) if (spinner != null ) { val adapter = ArrayAdapter( this , android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText( this @MainActivity , getString(R.string.selected_item) + " " + "" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } } } |
Spinner in Kotlin
Android Spinner is a view similar to a dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using the Adapter we can easily bind the items to the spinner objects. Generally, we populate our Spinner control with a list of items by using an ArrayAdapter in our Kotlin file. First, we create a new project by following the below steps:
- Click on File, then New => New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click the next button.
- Then select the Empty activity => next => finish.
Contact Us