Setting values and display Text in Android Spinner

kaibuki picture kaibuki · May 31, 2010 · Viewed 27.3k times · Source

I need help in setting up value and display text in spinner. as per now I am populating my spinner by array adapter e.g

mySpinner.setAdapter(myAdapter);

and as far as I know after doing this the display text and the value of spinner at same position is same. The other attribute that I can get from spinner is the position on the item.

now in my case I want to make spinner like the drop down box, which we have in .NET.

which holds a text and value.

where as text is displayed and value is at back end. so if I change drop down box , I can either use its selected text or value. but its not happening in android spinner case.

For Example:

Text Value
Cat 10
Mountain 5
Stone 9
Fish 14
River 13
Loin 17

so from above array I am only displaying non-living objects text, and what i want is that when user select them I get there value i.e. like when Mountain selected i get 5

I hope this example made my question a bit more clear...

thankx

Answer

alun picture alun · May 31, 2010

If you dont want to go through creating your own adapter-class you can instead wrap you data up in something that has toString returning what you want to show in the spinner. I use a class like this:

public class TextItemPair<T> {
    private String text;
    private T item;
    public TextItemPair(String text, T item) {
            this.text = text;
            this.item = item;
    }
    public String getText() {
        return text;
    }
    public T getItem() {
        return item;
    }
    @Override
    public String toString() {
        return getText();
    }
}

And when the spinner changes:

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    YourTypeHere t = ((TextItemPair<YourTypeHere>)spinner.getItemAtPosition(position)).getItem();
}