How to create a dropdown menu in Android?

Dropdown menus give the user a choice to choose a single options from a list of options in a dropdown. To create a dropdown menu, you need to use an XML widget called Spinner.

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/options"
    android:padding="5dp"/>

You need to use an XML attribute called entries to show the list of options.

android:entries="@array/options"

The entries attribute takes a string array where you can place each option as a separate item in the array. Place the string-array in strings.xml.

<string-array name="options">
    <item>Choose an option...</item>
    <item>Travel</item>
    <item>Mobile</item>
    <item>Food</item>
</string-array>

You can also initialise a spinner dynamically in Java by using an ArrayAdapter instead of using the entries attribute as follows:

Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.options, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);