Is it possibile to set hint Spinner in Android [duplicate]

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!


Solution 1:

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

Solution 2:

You can setup your own spinner adapter and overide the getView method to show the hint instead of an item . I have created a sample project on github , check it out here