Reputation: 2170
I know how to use EditText in android and how to use AutoComplete EditText in android. But AutoComplete EditText is used like dropdown list where user type a character and suggestions will be displayed and user clicks on one of the suggestions. If there is no suggestion then it won't display any text.
My requirement is like, Consider there is an EditText. User can type anything they want, but when the word starts from special character like for example "@" then the api will hit and display suggestions.
Complete Example:
"My Name is James Bond and I am @And"
In above example when user type this sentence at the end "@And" it will show the auto suggestion from hitting the API(should display Android) and user can select this suggested word from list.
Is there any way to achieve this??
Please Do help me.
Thank You.
Upvotes: 2
Views: 1259
Reputation: 2023
Android provides MultiAutoCompleteTextView
. Use this widget instead of EditText and override its tokenizer.
MultiAutoCompleteTextView myautocomplete = (MultiAutoCompleteTextView) findViewById(R.id.multy);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_for_autocomplete);
myautocomplete.setAdapter(adapter);
myautocomplete.setTokenizer(new MultiAutoCompleteTextView.Tokenizer() {
@Override
public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;
while (i > 0 && text.charAt(i - 1) != '@') {
i--;
}
while (i < cursor && text.charAt(i) == ' ') {
i++;
}
return i;
}
@Override
public int findTokenEnd(CharSequence text, int cursor) {
int i = cursor;
int len = text.length();
while (i < len) {
if (text.charAt(i) == ',') {
return i;
} else {
i++;
}
}
return len;
}
@Override
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && text.charAt(i - 1) == ' ') {
i--;
}
if (i > 0 && text.charAt(i - 1) == ',') {
return text;
} else {
if (text instanceof Spanned) {
SpannableString sp = new SpannableString(text + ", ");
TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
Object.class, sp, 0);
return sp;
} else {
return text + ", ";
}
}
}
});
Documentation : http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html
Upvotes: 1