我有键和值的列表, key = 是表中的 id 字符串。 value = 是一个名称字符串,
我想在微调器 View 中仅显示没有 ID 的值,但是在用户单击某个项目后,我需要获取所选项目的 Id,并在代码中使用它。 如何在不使用 hashMap 或许多 foreach 语句的情况下实现此结构?
谢谢,
最佳答案
创建一个 POJO 类并将自定义对象的 ArrayList
传递给微调器。
class MyClass{
private String id;
private String key;
public MyClass(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
重写toString()
方法很重要。这就是微调器项目中将显示的内容。
您可以将其传递给您的ArrayAdapter
,如下所示:
ArrayAdapter userAdapter = new ArrayAdapter(this, R.layout.spinner, myList);
当用户单击某个项目时,getSelectedItem()
方法将为您提供对象。您可以从那里获取 id
。
来自docs :
A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
关于java - 在没有 hashmap 结构的微调器中使用键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069692/