How to create a drop-down list?

simple / elegant / how I do it:

Preview:

enter image description here

XML:

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"/>

spinnerMode set to dropdown is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)

Java:

//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);

Documentation:

This is the basics but there is more to be self taught with experimentation.
https://developer.android.com/guide/topics/ui/controls/spinner.html

  1. You can use a setOnItemSelectedListener with this. (https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener)
  2. You can add a strings list from xml. (https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate)
  3. There is an appCompat version of this view. (https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)

Leave a Comment