Java how to set list data to android spinner

Java how to set list data to android spinner

To set a list of data to an Android Spinner, you can use the setAdapter method and pass it an instance of ArrayAdapter.

Here is an example of how to set a list of strings to a Spinner:

re‮al:ot ref‬utturi.com
List<String> items = Arrays.asList("item1", "item2", "item3");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(adapter);

In the example above, this refers to the Activity or Context where the Spinner is located, R.id.spinner is the ID of the Spinner in the layout file, and items is the list of strings that you want to display in the Spinner.

The ArrayAdapter constructor takes three arguments: the Context, the layout resource for the dropdown items, and the list of items. The layout resource for the dropdown items is specified using the setDropDownViewResource method.

You can also use a custom layout for the dropdown items by creating a layout resource file and passing it to the ArrayAdapter constructor instead of using android.R.layout.simple_spinner_item.

Once you have created the ArrayAdapter and set it to the Spinner using setAdapter, the list of items will be displayed in the Spinner when it is displayed on the screen.

Created Time:2017-11-03 23:27:12  Author:lautturi