我有Spinner可以通过字符串从资源中选择文件,但我希望在Spinner中显示其他名称..现在工作正常,但显示名称pic.jpg ..我想要文本和值
文本
String s = {"picture car" , "picture mobile"}
和值
String[] spinnerValue = {"pic.jpg", "pic2.jpg"};
spinnerDropDownView =(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<>(test.this, android.R.layout.simple_list_item_1, spinnerValue);
spinnerDropDownView.setAdapter(adapter);
答案 0 :(得分:0)
使用具有键值对pojo模型的Spinner适配器 请参阅以下代码以获取更多详细信息
步骤1:创建将处理密钥和
的POJO类@Override
public void serialize(Map<String, Object> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
Map<String, Object> adaptedValue = new HashMap<>(value);
for (Map.Entry<String, Object> e : value.entrySet()) {
if (e.getValue() instanceof Date) {
adaptedValue.put(e.getKey() + "[date]", ((Date) e.getValue()).getTime());
adaptedValue.remove(e.getKey());
}
}
new ObjectMapper().writeValue(gen, adaptedValue);
}
注意:toString()方法很重要,因为它负责在微调器中显示数据,你可以根据需要修改toString()
步骤2:准备要在微调器中加载的数据
public class Country {
private String id;
private String name;
public Country(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//to display object as a string in spinner
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Country){
Country c = (Country )obj;
if(c.getName().equals(name) && c.getId()==id ) return true;
}
return false;
}
}
步骤3:最后在微调器的onitemselected侦听器方法中获取所选项的键和值
private void setData() {
ArrayList<Country> countryList = new ArrayList<>();
//Add countries
countryList.add(new Country("1", "India"));
countryList.add(new Country("2", "USA"));
countryList.add(new Country("3", "China"));
countryList.add(new Country("4", "UK"));
//fill data in spinner
ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(context, android.R.layout.simple_spinner_dropdown_item, countryList);
spinner_country.setAdapter(adapter);
spinner_country.setSelection(adapter.getPosition(myItem));//Optional to set the selected item.
}