Android: Spinner add hint and avoid initial call trick
Are you facing these two problems with the Spinner API?
- Your onItemSelected() callback is called immediately when you set your spinner listener.
- There is no hint to show.
I got you cover with a quick and small footprint solution.
This is the end result:
Standard Spinner UI, nice hint text and full clickable area.
On Select, notice the extra item as hint:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
String[] items = new String[] {"Choose One", "item0", "item1", "item2", "item3"}; // set hint spinner.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, items)); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long Id) { if (i == 0) { // When user clicked on "Choose One" hint and the initial call. return; } i--; // undo the "Choose One" hint. // Your business logic // i = 0 map to item0 // i = 1 map to item1 // ... } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); |
There are two popular Stack Overthrow questions on each of this problem:
How to keep onItemSelected from firing off on a newly instantiated Spinner?
How to make an Android Spinner with initial text “Select One”?
Answers above include using a boolean flag or creating a new Class, but solve just one of the problem. This solution is more straightforward, easy to read & maintain, and kills two birds with one stone.