How can I add a hint to the Spinner widget?

android, hint, spinner, user-interface

Solution

I haven't found an easy and clean solution yet, only this workaround using custom adapters and a custom item class:

First, we need a class for the spinner item content:

class SpinnerItem {
        private final String text;
        private final boolean isHint;

        public SpinnerItem(String strItem, boolean flag) {
            this.isHint = flag;
            this.text = strItem;
        }

        public String getItemString() {
            return text;
        }

        public boolean isHint() {
            return isHint;
        }
    }

Then our adapter class:

class MySpinnerAdapter extends ArrayAdapter<SpinnerItem> {
        public MySpinnerAdapter(Context context, int resource, List<SpinnerItem> objects) {
            super(context, resource, objects);
        }

        @Override
        public int getCount() {
            return super.getCount() - 1; // This makes the trick: do not show last item
        }

        @Override
        public SpinnerItem getItem(int position) {
            return super.getItem(position);
        }

        @Override
        public long getItemId(int position) {
            return super.getItemId(position);
        }

    }

Finally we use the workaround like this:

ArrayList<SpinnerItem> items = new ArrayList<SpinnerItem>();
        items.add(new SpinnerItem("Item 1", false));
        items.add(new SpinnerItem("Item 2", false));
        items.add(new SpinnerItem("HINT", true)); // Last item 

        MySpinnerAdapter adapter = new MySpinnerAdapter(this, android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(items.size() - 1);

Then you can use the flag from the SpinnerItem class to set text color for that item or whatever.

Problem

I have a `Spinner` in `spinnerMode="dropdown"` mode. Instead of the preselected first item, I want to show the user a hint, so that there is no default selection (like »Please select an item«) This is the UI I got: and this is the UI I want to achive: I figured that the `EditText` widget has an `android:hint` attribute, but not the `Spinner` widget and setting it doesn't bring me the the UI I want. This is an Android 4.x-only app, so I don't have to hassle with any pre-4.0 compatibility stuff.

Original source

Related problems