Langsung ke konten utama

Tutorial To Create Spinner (DropDown List) On Android

Today we are going to learn on how to create Spinner in Android. Spinner is one of the views that we see a lot almost in every Android application.

Spinner is simply a dropdown list containing items we can choose. Spinner is made to ease users selecting one value from a list/array that's presented quickly.

How to create Spinner on Android using Android Studio


Basically there are two methods to use for creating Spinner in Android based on data source that we want to present.

First method, using array data that is stored in the resource .xml file in the form of string-array. This method is useful if the list value on Spinner has static behavior -- Not being changed.

Second method, to create Spinner in Android using array data stored in Java file, in form of String array or String ArrayList. This second method is useful if we want to present dynamic data on the list. For example like fetching array from server first before being presented to Spinner.
    And the two methods above will be discussed on this occasion. Just keep reading.

    Method 1. Creating Spinner on Android using String-Array in XML


    Step 1 -- Here we will create Spinner with list data stored in XML file as string-array.

    Step 2 -- First off, we need to create a new project first using Android Studio. Visit this page to learn to do it.

    Step 3 -- After that, we need to open strings.xml file on res/values folder, then enter the string-array as follow.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <string-array name="german_familienname">
        <item>Fischer</item>
        <item>Bauer</item>
        <item>Scheider</item>
        <item>Jäger</item>
        <item>Müller</item>
        <item>Schulz</item>
        <item>Neumann</item>
        <item>Schwarz</item>
        <item>Lange</item>
        <item>Köhler</item>
        <item>Schumacher</item>
    </string-array>

    Step 4 -- The next step is, on activity_main.xml layout we need to add a Spinner view and a button to become like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:paddingStart="50dp"
        android:paddingEnd="50dp"
        android:paddingLeft="50dp"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Spinner
            android:padding="20dp"
            android:id="@+id/sp_name"
            android:entries="@array/german_familienname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></Spinner>
        <Button
            android:id="@+id/bt_check"
            android:text="Submit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    Step 5 -- Now the question is: "How to fetch the selected value on Spinner?" The answer is very simple, simply open MainActivity.java file and do a logic coding there.

    So the flow is we choose value on the Spinner, then while the Button is clicked, then the value name will be displayed.

    Step 6 -- The following is the example code on MainActivity.java.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    /**
     * Created by Android Flash Tools on 15/04/2016.
     */
    public class MainActivity extends AppCompatActivity {
        private Spinner spNamen;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spinner);
            spNamen = (Spinner) findViewById(R.id.sp_name);
            Button btSpinner = (Button) findViewById(R.id.bt_check);
            btSpinner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(TWOHLayoutSpinner.this, "Selected "+ spNamen.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    That's it. Because the Spinner has already being filled with list from XML, so when we click on the Button, we simply call getSelectedItem() method that automatically fetch which item we have selected and change it into String with toString() method.

    Result


    Create Spinner Using String-Array Data In XML

    Now we go to the second method.

    Method 2. Creating Spinner using dynamic data like String Array / ArrayList


    In this second method we don't need to add string-array on xml resource, because the data list for the Spinner will be fetched directly from its Activity in the form of Array / ArrayList. We will use SpinnerAdapter that allows us to manage array data string so can be displayed on Spinner.

    Step 1 -- Firstly we need to add one more Spinner view in the activity_main.xml, like this.

    1
    2
    3
    4
    5
    <Spinner
        android:padding="20dp"
        android:id="@+id/sp_name_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Spinner>

    Notes. The above Spinner doesn't come with android:entries attribute because we don't need to use that attribute to insert data in Spinner, differ from the first method.

    Step 2 -- And the main codes on MainActivity.java file as follow.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    /**
     * Created by Android Flash Tools on 15/04/2016.
     */
    public class MainActivity extends AppCompatActivity {
        private Spinner spNamen2;
        private String[] germanFeminine = {
                "Karin",
                "Ingrid", "Helga",
                "Renate",
                "Elke",
                "Ursula",
                "Erika",
                "Christa",
                "Gisela",
                "Monika"
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spinner);
            spNamen2 = (Spinner) findViewById(R.id.sp_name_2);
            // inisialiasi Array Adapter dengan memasukkan string array di atas
            final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, germanFeminine);
            // mengeset Array Adapter tersebut ke Spinner
            spNamen2.setAdapter(adapter);
            // mengeset listener untuk mengetahui saat item dipilih
            spNamen2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    // memunculkan toast + value Spinner yang dipilih (diambil dari adapter)
                    Toast.makeText(TWOHLayoutSpinner.this, "Selected "+ adapter.getItem(i), Toast.LENGTH_SHORT).show();
                }
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {
                }
            });
        }
    }

    Step 3 -- If we look carefully from the above code, the new thing added is String[] array containing data to be used in the Spinner.

    But don't forget to insert that String array inside the Spinner, we have to use ArrayAdapter for that. After that, we can set OnItemSelectedListerner() on Spinner.

    For us to be able monitoring Spinner state when a user finished selecting an item on Spinner. Then it will show Toast containing the selected Spinner item value.

    Result


    Create Spinner Using String-Array / ArrayList

    Komentar

    Postingan populer dari blog ini

    How To Create Android App Using Android Studio (Complete Guides)

    How to create Android App using Android Studio (Complete Guides). Hi guys today I would like to share a tutorial on how to create Android app using Android Studio.

    Surely you have fully aware that currently Android Studio had been ordained to be the most recommended IDE officially by Google to help users creating an Android app.

    Download MTK SP Multi Port Download Tool To Flash Scatter File On MediaTek

    Download MTK SP Multi Port Download Tool to flash scatter file (Firmware) on MediaTek smartphone or tablet. The tool is provided for free and can run on Windows operating system based computer.
    On this post I have managed to list some newest versions of MTK SP Multi Port Download Tool and also explain to you the tool's features.

    If you've been searching a tool to upgrade or downgrade your device with firmware then MTK SP Multi Port Download Tool can be your consideration.

    Features of MTK SP Multi Port Download Tool
    Install Firmware.

    You can install scatter file / firmware to your MediaTek devices. You just need to connect your device to computer then launch the tool and continued with click on the Flash to start the flashing procedures.

    Format Bootloader.

    You can also format or even delete your device's bootloader using this tool. But remember doing that will effect on bootloop to your device if you are not careful.

    Set Flashing Speed.

    For the flashing, you are given with a two…