我从api(我存储在模型中的带有ID的名称列表)中获取值-如何将此名称设置为AutoComplete并在下拉选择中同时获取名称和ID。 这将在自动完成中设置一个名称,并在onItemClick上获取名称,但是如何获取ID?
模型类
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
MyActivity类 OnCreate: 调用自动完成适配器
setMeetingContactAuto(autoContact, contactList);
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
strContact =(String) parent.getItemAtPosition(position);
// strContactCode = code.get(position);
}
});
private void setMeetingContactAuto(AutoCompleteTextView autoContact, final ArrayList<MeetingContactModel> xcontactList) {
List<String> names = new AbstractList<String>() {
@Override
public int size() { return xcontactList.size(); }
@Override
public String get(int i) {
code.clear();
code.add(xcontactList.get(i).getText());
return xcontactList.get(i).getText();
}
};
autoContact.setThreshold(1);
autoContact.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
}
无法获取ID-请让我知道获取它
答案 0 :(得分:3)
在模型类中实现toString()方法
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}
// Fetch your selected model
autoContact.setAdapter(new ArrayAdapter<>(requireContext(), R.layout.spinner_item_ranking, contactList));
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MeetingContactModel m=(MeetingContactModel) parent.getItem(position);
String name=m.getText();
String id=m.getId();
}
});