Setting ID for Spinner items

后端 未结 5 2075
温柔的废话
温柔的废话 2020-12-25 12:50

I have an array of Strings I\'m populating a Spinner object with. However, I\'d like to attach an ID to each element of the Spinner, so when the user selects an item, I hav

5条回答
  •  我在风中等你
    2020-12-25 13:00

    Create a class StringWithTag and use in place of the string name in the list like so :-

    public class StringWithTag {
        public String string;
        public Object tag;
    
        public StringWithTag(String stringPart, Object tagPart) {
            string = stringPart;
            tag = tagPart;
        }
    
        @Override
        public String toString() {
            return string;
        }
    }
    

    in the add items to spinner part :-

    List list = new ArrayList();
    list.add(new StringWithTag("Oldman", "12345"));
    list.add(new StringWithTag("Umpire", "987654"));
    list.add(new StringWithTag("Squad", "ABCDEE"));
    ArrayAdapter adap = new ArrayAdapter (this, android.R.layout.simple_spinner_item, list);
    ....
    ....
    

    in the listener :-

    public void onItemSelected(AdapterView parant, View v, int pos, long id) {
        StringWithTag s = (StringWithTag) parant.getItemAtPosition(pos);
        Object tag = s.tag;
    }
    

    voila! }

提交回复
热议问题