SATURN  RING  STATION

At a distant space view post, we chat about codes.

Android: Spinner add hint and avoid initial call trick

Are you facing these two problems with the Spinner API?

  1. Your onItemSelected() callback is called immediately when you set your spinner listener.
  2. 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:

 



    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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Android: Spinner add hint and avoid initial call trick