Android Spinner is a view similar to the 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 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.
Different Attributes for Spinner Widget
|android:id||Used to specify the id of the view.|
|android:textAlignment||Used to the text alignment in the dropdown list.|
|android:background||Used to set the background of the view.|
|android:padding||Used to set the padding of the view.|
|android:visibilty||Used to set the visibility of the view.|
|android:gravity||Used to specify the gravity of the view like center, top, bottom, etc|
Example to demonstrate the Spinner
Here is an example of an Android application that displays the list of courses of GFG. Use ArrayAdapter to store the courses list. Create a single MainActivity that contains the spinner and on clicking any item of spinner Toast with that course name will be shown.
Creating the activities: There will be one activity and hence one XML file for MainActivity. activity_main.xml: XML file for first activity consists of constraint layout with spinner widget. Below is the code for the XML file for activity:
Creating the Java and Kotlin file: There is one activity and hence one Java/Kotlin file for the MainActivity file. Java/Kotlin file for Main Activity, in which Array Adapter is used to bind data to the spinner. We will fill data in the array of strings and bind that data to the spinner. Here is the code:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.