Select Item in Spinner - Android

杀马特。学长 韩版系。学妹 提交于 2019-12-06 07:28:30

items class

public class items {
private String name;
private int id;

public String getname() {
    return name;
}
public void setname(String name) {
    this.name = name;
}

public int getid() {
    return id;
}
public void setid(int id) {
    this.id =id;
}
@Override
public String toString() {
    return name;
}
}

now adding items to array list like this

List<items> values1=new ArrayList();
items comment = new items();
    comment.setname("name1");
    comment.setid("id1");
values1.add(comment);
ArrayAdapter<items> dataAdapter = new ArrayAdapter<String>(
                    this, android.R.layout.simple_spinner_item, list);...

as you did in your code from here.. set onitemselected listener like this...

sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
items item1 = (items)arg0.getItemAtPosition(arg2);
int id= item1.id<---- get id here..

Make a pojo class of your own say Item and add two fields in it, id and name.
Then make a list of those items and write your own adapter for the spinner, and use it.
It will return you the whole object of the Item class when you click any item of it.

Else, if the item ids are the sequential then you can map them with the item ids too and can carry on with the same implementation, you have done right now.

But first approach is the recommended one, as you are developing using an Object oriented language and your data structures must represent the actual objects of your requirement in the application.

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
    // TODO Auto-generated method stub


    //code one
    String arr[]=getResources().getStringArray(R.array.days);

    text1.setText(arr[arg2]);

    //or 

    //code two
    text1.setText(((TextView)arg1).getText());
}

Create new enum:

public enum EnumerateThis {
    ENUM1(0, "Use this like a value"),
    ENUM2(1, "and first argumenta like an integer id");

    private Integer id;
    private String descr;

    private EnumerateThis (Integer id, String place){
        this.id = id;
        this.descr = place;
    }

    public Integer getId() {
        return id;
    }

    public String getDescr() {
        return descr;
    }
}

than using spinner adapter:

ArrayAdapter<EnumerateThis> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, EnumerateThis.values());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!