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.
Modify activity_main.xml file
In this file, we use the TextView widget and also set its attributes.
Update strings.xml file
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.
Create Spinner in MainActivity.kt file
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)
Run as Emulator: