Dynamic Spinner in Kotlin - GeeksforGeeks

28 Mar, 2022
Android Spinner is a view similar to 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.
Default value of the android spinner will be currently selected value and by using Adapter we can easily bind the items to spinner object.Here, we will create the spinner programmatically in 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 next button.Then select the Empty activity => next => finish.
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 next button.
Then select the Empty activity => next => finish.
In this file, we use the TextView widget and also set its attributes.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/linear_layout"    android:gravity = "center">      <TextView        android:id="@+id/txtView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Select language:"        android:textSize = "20dp" />  </LinearLayout>
Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu.
XML
<resources>    <string name="app_name">SpinnerInKotlin</string>    <string name="selected_item">Selected item:</string>      <string-array name="Languages">        <item>Java</item>        <item>Kotlin</item>        <item>Swift</item>        <item>Python</item>        <item>Scala</item>        <item>Perl</item>    </string-array></resources>
First, we declare a variable languages to access the strings items from the strings.xmnl file.
val languages = resources.getStringArray(R.array.Languages)

then, we can create the spinner using
val spinner = Spinner(this)
    spinner.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)

Add the spinner in the linear Layout using
val linearLayout = findViewById<LinearLayout>(R.id.linear_layout)
        //add spinner in linear layout
        linearLayout?.addView(spinner)

Kotlin
package com.geeksforgeeks.myfirstkotlinapp  import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport 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)          //create spinner programmatically        val spinner = Spinner(this)        spinner.layoutParams = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.WRAP_CONTENT,            ViewGroup.LayoutParams.WRAP_CONTENT)          val linearLayout = findViewById<LinearLayout>(R.id.linear_layout)        //add spinner in linear layout        linearLayout?.addView(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                }            }        }    }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp">  <application    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:roundIcon="@mipmap/ic_launcher_round"    android:supportsRtl="true"    android:theme="@style/AppTheme">    <activity android:name=".MainActivity">        <intent-filter>            <action android:name="android.intent.action.MAIN" />              <category android:name="android.intent.category.LAUNCHER" />        </intent-filter>    </activity></application>  </manifest>
 
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
Android Menus
ImageView in Android with Example
How to Get Current Location in Android?
Kotlin Android Tutorial
How to Convert Kotlin Code to Java Code in Android Studio?
Kotlin when expression
MVP (Model View Presenter) Architecture Pattern in Android with Example
ScrollView in Android