simple / elegant / how I do it:
Preview:
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
- You can use a setOnItemSelectedListener with this. (https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener)
- You can add a strings list from xml. (https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate)
- There is an appCompat version of this view. (https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)