[英]How to get adapter item position from AutoCompleteTextView?
String[] idArray = {"1","2","3","4"};
String[] nameArray = {"Abraham","Abhi","John","Joseph"};
final ArrayAdapter<String> adapterTextView = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,nameArray);
etItemName.setAdapter(adapterTextView);
etItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String id = idArray[position];
}
});
This is my code. 这是我的代码。 In this, when I type "Jo", John and Jospeh are populating on AutoCompleteTextView
and when I selected John I get String id
as 0 . 在这种情况下,当我键入“ Jo”时, John和Jospeh会在AutoCompleteTextView
上填充,并且当我选择John时,我会得到String id
为0 。 But actually I need is 2 . 但实际上我需要的是2 。 So how can I get 2 instead of 0 ? 那么我怎样才能得到2而不是0呢?
This is not the perfect solution but you can take it as the last option: 这不是完美的解决方案,但您可以将其作为最后的选择:
When you pass the selected string just loop through your nameArray to find its position: 当您传递选定的字符串时,只需遍历nameArray即可找到其位置:
int position=-1;
for(int i=0;i<nameArray.length;i++){
if(selectedItem.equalsIgnoreCase(nameArray[i])){
position=i;
}
}
@Shaheer Palollathil n9153's suggestion would work. @Shaheer Palollathil n9153的建议会起作用。 I'm just changing his answer according to your code. 我只是根据您的代码更改他的答案。
AutoCompleteTextView t;
t.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = -1;
for(int i = 0; i < nameArray.length; i++){
if(((AutoCompleteTextView)view).getText().toString().equals(nameArray[position]))
pos = position;
break;
}
String id = idArray[pos]; // should be your desired number
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.