How to create a drop-down list?

user1820528 picture user1820528 · Nov 14, 2012 · Viewed 545.8k times · Source

How can I create a drop-down list? I've tried a ScrollView but it's not exactly what I need.

Answer

Nicolas Tyler picture Nicolas Tyler · Jul 15, 2013

Best way to do it is:

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"/>

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);

Notes:

  1. You can use a setOnItemSelectedListener with this.
  2. You can add a strings list from xml
  3. There is an appCompat version of this view.

More information:

This is the basics but there is more to be self taught with experimentation.

https://developer.android.com/guide/topics/ui/controls/spinner.html