I want to use a Spinner that initially (when the user has not made a selection yet) displays the text “Select One”. When the user clicks the spinner, the list of items is displayed and the user selects one of the options. After the user has made a selection, the selected item is displayed in the Spinner instead of “Select One”.
I have the following code to create a Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
With this code, initially the item “One” is displayed. I could just add a new item “Select One” to the items, but then “Select One” would also be displayed in the dropdown list as first item, which is not what I want.
How can I fix this problem?
Here’s a general solution that overrides the
Spinnerview. It overridessetAdapter()to set the initial position to -1, and proxies the suppliedSpinnerAdapterto display the prompt string for position less than 0.This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private
AdapterView.setNextSelectedPositionInt()andAdapterView.setSelectedPositionInt(), it’s not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.Normally I wouldn’t condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.