![](/img/trans.png)
[英]How to get the selected item from a AutoCompleteTextView with a custom Adapter
[英]How to get array index of selected item from AutoCompleteTextView?
我有一个来自数据库的用户数据谎言名称等,该数据库正在填充到AutoCompleteTextView中,但ItemCLickListener中的位置与自动完成列表中显示的位置相同。 我想要数组索引,并且从适配器获取字符串将不起作用,因为相同的名称也可以存在。
更新资料
例如。 在数据库中,我有4个条目abc,xyz,abc,pqrq以及其他字段中的一些其他数据。 这些名称存储在数组中。
因此,当我单击abc时,我也希望获取其他数据,这只有在我知道所选项目的数组索引的情况下才能完成。
救命!
解决方案:
范例: https : //www.androidcode.ninja/android-autocompletetextview-custom-arrayadapter-sqlite/
您应该创建一个包含自定义对象的数组,而不是使用Strings
数组。
首先,创建一个新的class
如下所示:
class CustomObject {
public long id;
public String name;
public CustomObject(long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return name;
}
}
然后,您将从数据库中获取数据,该数据将为Strings
,而不是仅存储String
还可以向数组添加唯一的 ID,我们稍后将使用它。
因此,例如,您可以像这样填充数组:
// this array should contain the items from your database, and a unique id
final CustomObject[] items = { new CustomObject(0, "test"), new CustomObject(1, "test"),
new CustomObject(2123123, "another name")};
然后使您的AutoCompleteTextview
点击检测器如下所示:
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject customObject = (CustomObject) parent.getItemAtPosition(position);
int index = -1;
for (int i = 0; i < items.length; i++) {
if (items[i].id == customObject.id) {
index = i;
break;
}
}
// now we have your index :)
Toast.makeText(MainActivity.this, "Your index = " + index,
Toast.LENGTH_SHORT).show();
}
});
就是这样,这里有您需要的索引。 请注意,对于大型阵列,此方法将很慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.