Reputation: 23
I am using an AutoCompleteTextView in my app which gives countries names suggestions. My autocomplete is matching the entered text with every word in the suggestions list. For example, if I enter the two letters "ar", I get "Saudi Arabia" as one of the suggestions.
Is there any way to make the AutoCompleteTextView tries to match only starting from the first word? i.e. the suggestion must start with entered text, in case of my previous example, I get suggestions like "Armenia", "Argentina" & "Aruba" only.
Upvotes: 2
Views: 2355
Reputation: 2153
The problem is the Filter
implementation within ArrayAdapter
first checks if the string starts with the search constraint, and then splits the string and checks each individual word.
From ArrayAdapter.java:
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
// Start at index 0, in case valueText starts with space(s)
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
As Daniel mentioned, you will need to implement your own adapter that implements Filterable
. I've created an example that achieves the behavior you're looking for. You can find it here. It reuses most of the code within ArrayAdapter
, but omits the part that splits the strings.
Upvotes: 4
Reputation: 16910
You need to write an adapter, which supplies the items, and implements the Filterable interface.
For using the Filterable in the adapter, see this gist.
Basically you need to do a check with abc.startsWith(xyz)
, and filter the results based on that.
Upvotes: 0