Android Spinner: How to Create Dropdown Lists

To display a dropdown menu (Spinner) in an Android application, you can use the Spinner control. Here are the steps to implement it:

  1. Add a Spinner control to the layout file.
<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  1. Locate the Spinner control in the Activity and set an adapter for it.
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

In the code above, R.array.spinner_items is a string array resource defined in the res/values/strings.xml file, which includes the options content in the dropdown menu.

  1. Set a selection listener for the drop-down menu options.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // 处理选中项的逻辑
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // 处理未选中任何项的逻辑
    }
});

By following these steps, you can display a dropdown menu in your Android application and interact with the user’s selection.

bannerAds