Android Spinner (Drop Down) Example

This tutorial is about the Android spinner, which is a drop down list. In this example, we will learn to populate the Android spinner. Then we will display some content corresponding to the spinner element click (we will handle the spinner onclick event).
Spinners provide an easy and elegant way to select one value from list of values. By default, a spinner shows its current selected value. On touching, the spinner will display a drop down list containing all other available options from which the user can select a new value.

Android Spinner Example

In this spinner example, we are displaying a list of users inside the spinner. On clicking the spinner, a drop down list containing users will be displayed. When you click on any user (spinner item), the details corresponding to that user will be displayed in the fields below. So you will also learn how to handle the click event.
android-spinner-onclick
XML layout file:
Create a new file activity_main.xml
  • The spinner is used to hold a drop down list. It will display a list of users.
  • Two TextBoxes  are used to display the details(name and id) of the selected user.
    Listing 1 :
Corresponding to each spinner item (each user), there is an associated ID and name. We will store that in an arraylist so that we can display it accordingly on the spinner item click.
Create a new file Users.java
Listing 2 :

The code to populate a spinner

Now we will write the main code to populate a spinner and handle the click events.
  1. We will create a new arraylist and store the list of “users” inside it.
  2. We need an adapter to populate a spinner. Here we are using the ArrayAdapter to fill our data inside the spinner.
  3.  We populate the spinner by attaching the adapter using the lines of code below. The ArrayAdapter takes three arguments. The first argument is the reference of the activity in which spinner is located. The second argument tells us that we are using a simple drop down layout. The third argument is our arraylist containing data for the spinner.
    Snippet 1 :
Now let’s see the complete code first. Then I will explain the click event for the spinner item.
MainActivity.java
Listing 3 :
We will use setOnItemSelectedListener to handle the click events for us. When you click on a spinner item, the control will go to the onItemSelected method. Here we can implement the logic for handling the click events. In our case, we are displaying the name and ID associated with the selected user.
Snippet 2 :
This was all about a drop down list in Android. If you have any doubts or suggestions regarding this Android spinner example, then feel free to comment in the section below. Thank You for reading.

Comments

Popular posts from this blog

သခ်ၤာ တြက္ခ်က္မႈ ဆိုင္ရာ နည္းလမ္းမ်ား

Software Development Library