[英]How to get array index of selected item from AutoCompleteTextView?
I have a user data lie names etc. coming from database which is being populated to AutoCompleteTextView but the position in ItemCLickListener is of the position as displayed in the auto complete list. 我有一个来自数据库的用户数据谎言名称等,该数据库正在填充到AutoCompleteTextView中,但ItemCLickListener中的位置与自动完成列表中显示的位置相同。 I want the array index, and getting string from the adapter won't work because the same names can be there too.
我想要数组索引,并且从适配器获取字符串将不起作用,因为相同的名称也可以存在。
Update 更新资料
eg. 例如。 In the database I have 4 entries abc, xyz, abc, pqrq along with some other data in other fields.
在数据库中,我有4个条目abc,xyz,abc,pqrq以及其他字段中的一些其他数据。 These names are stored in an array.
这些名称存储在数组中。
So when I click abc, I want the other data to be fetched as well which could be done only if I know the array index of selected item. 因此,当我单击abc时,我也希望获取其他数据,这只有在我知道所选项目的数组索引的情况下才能完成。
Help! 救命!
Solution : 解决方案:
sample : https://www.androidcode.ninja/android-autocompletetextview-custom-arrayadapter-sqlite/ 范例: https : //www.androidcode.ninja/android-autocompletetextview-custom-arrayadapter-sqlite/
Instead of using an array of Strings
, you should create an array with custom objects in it. 您应该创建一个包含自定义对象的数组,而不是使用
Strings
数组。
First, create a new class
like this: 首先,创建一个新的
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;
}
}
Then, you get data from your database, which will be Strings
, instead of storing only a String
you can also add a unique id to the array which we will we use later. 然后,您将从数据库中获取数据,该数据将为
Strings
,而不是仅存储String
还可以向数组添加唯一的 ID,我们稍后将使用它。
So, for example, you can fill the array like this: 因此,例如,您可以像这样填充数组:
// 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")};
Then make your AutoCompleteTextview
click detector look like this: 然后使您的
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();
}
});
And that's it, there is the index you need. 就是这样,这里有您需要的索引。 Note that for large arrays, this method will be slow.
请注意,对于大型阵列,此方法将很慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.