Is it possibile to set hint Spinner in Android

Nick picture Nick · Jul 6, 2011 · Viewed 83.6k times · Source

Is there anyway of making a hint for a spinner similar to hint that is provided for edit text fields. I know you can use a prompt that gives you a title bar but still leaves the initial spinner field blank until you click into the spinner. I currently have a crude way of setting a dummy field as the first part of the spinner array which is the question and then have a check at the end to make sure the spinner doesn't equal the question string. Is there any cleaner / better way of doing this?

Thanks!

Answer

Boni2k picture Boni2k · Sep 12, 2012

Here's a solution which is probably a bit simpler than Ravi Vyas code (thanks for the inspiration!):

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item) {

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = super.getView(position, convertView, parent);
        if (position == getCount()) {
            ((TextView)v.findViewById(android.R.id.text1)).setText("");
            ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
        }

        return v;
    }       

    @Override
    public int getCount() {
        return super.getCount()-1; // you dont display last item. It is used as hint.
    }

};

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Item 1");
adapter.add("Item 2");
adapter.add("Hint to be displayed");

spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //display hint