如何将对象传递给android中的微调器?

时间:2017-01-11 10:47:34

标签: java android spinner

代码是:

public class Organization {

private String name;
private Long id;

public Organization(){
}

public Organization(String name, Long id) {
    super();
    this.name = name;
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}
}

微调器是:

 Spinner sp = (Spinner) navigationView.getMenu().findItem(R.id.brand_spinner).getActionView();
 sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,contactList));
 sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String value = parent.getItemAtPosition(position).toString();
            Toast.makeText(parent.getContext(),""+value+"",Toast.LENGTH_SHORT).show();
        }
 });

如何通过在微调器中选择名称,将名称和id传递给微调器,并且应该在微调器中列出。将名称的id存储在局部变量中。

2 个答案:

答案 0 :(得分:0)

您必须创建自己的自定义适配器类,该类将扩展$newArray = array(); foreach($arrayData as $key => $value) { foreach($value as $key2 => $value2) { $newArray[$key2] = $value2; } } BaseAdapter,并且您只需传递ArrayAdapter的{​​{1}}。

只需检查此链接,它将帮助您创建适配器

Check Link

答案 1 :(得分:0)

对于ArrayAdapter,您要发送contactList,覆盖contactList对象中的toString()。因此ArrayAdapter在渲染时会调用toString()方法,contactList的每个对象都在textView中显示文本。

现在点击项目,

sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
        @Override 
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            Object obj= parent.getItemAtPosition(position);
            Contact c = (Contact) obj;
            System.out.println("id = " + c.getId() + " , Name = " + c.getName());

 }