开发者

Setting values and display Text in Android Spinner

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 t开发者_Go百科ext 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


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();
}


Step #1: Create a data model for your text and value pair

Step #2: Extend BaseAdapter or ArrayAdapter to wrap around your data model, overriding getView() to return whatever you want to display in the Spinner itself

Step #3: On a selection event, use the position to find the corresponding object in your data model, and look up the value

If all you want to display in the Spinner is just a text representation of each element in the data model, you can skip the custom Adapter -- just use ArrayAdapter<YourModelClass> and override toString() on YourModelClass to return whatever display text you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜