Android spinners are not nothing but the dropdownlist seen in other programming languages. It provides a easy way to select
value from list. Clicking spinner will display a dropdownlist with the available values.
In this tutorial, we show you how to do the following tasks :
1.Render a Spinner in XML, and load the selection items via XML file also.
2.Render another Spinner in XML, and load the selection items via code dynamically.
3.Attach a listener on Spinner, fire when user select a value in Spinner.
4.Render and attach a listener on a normal button, fire when user click on it, and it will display selected value of Spinner.
List of Items in Spinner
Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).
<!--?xml version= "1.0" encoding= "utf-8" ?--> assert value>= 18 : " Not valid" ; |
<!--?xml version= "1.0" encoding= "utf-8" ?--> <resources> <string name= "app_name" >MyAndroidApp</string> <string name= "country_prompt" >Choose a country</string> <string-array name= "country_arrays" > <item>Malaysia</item> <item>United States</item> <item>Indonesia</item> <item>France</item> <item>Italy</item> <item>Singapore</item> <item>New Zealand</item> <item>India</item> </string-array> </resources> |
Spinner (DropDown List)
Open “res/layout/main.xml” file, add two spinner components and a button.
In “spinner1”, the “android:entries” represents the selection items in spinner.
In “spinner2”, the selection items will be defined in code later.
<!--?xml version= "1.0" encoding= "utf-8" ?--> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:orientation= "vertical" > <spinner android:id= "@+id/spinner1" android:layout_width= "match_parent" android:layout_height= "wrap_content" android:entries= "@array/country_arrays" android:prompt= "@string/country_prompt" > <spinner android:id= "@+id/spinner2" android:layout_width= "match_parent" android:layout_height= "wrap_content" > <button android:id= "@+id/btnSubmit" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "Submit" > </button></spinner></spinner></linearlayout> |