How can I add a hint to the Spinner widget? [duplicate] How can I add a hint to the Spinner widget? [duplicate] android android

How can I add a hint to the Spinner widget? [duplicate]


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.