2

I have an Android Spinner widget in which I'd like to display a slightly different string for the first item if it's selected vs. if it's being displayed in the drop-down. For example, clicking

[Select a dessert...  v]

Pops up:

o No dessert
  Cake
  Pie
  Ice cream

If e.g. "Cake" is chosen, the Spinner behaves normally:

[Cake                 v]

But if "No dessert" is chosen, Select a dessert... should be used as the Spinner prompt, as when nothing was selected.

What's the easiest way to do this?

2 Answers2

5

Assuming you're using an approach similar to the one below, the simple_spinner_dropdown_item defaults to the toString() value of the object in the adapter. With that in mind, override the toString() method of some custom ListItem class to return whatever value you want the spinner to display when the item is being shown as a dropdown item. Meanwhile override the getView for the item selected in the adaptor.

ArrayAdapter<ListItem> adapter = new ArrayAdapter<ListItem>(this, android.R.layout.simple_spinner_item, items){
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View v = vi.inflate(android.R.layout.simple_spinner_item, null);
        final TextView t = (TextView)v.findViewById(android.R.id.text1);
        t.setText("Something else");
        return v;
    }
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ddlSpinner.setAdapter(adapter);
Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
0

First of all, set a android:prompt="Select a dessert..." inside the <Spinner>.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295