我正在尝试在android中创建一个标记机制,在写出描述时,当按下“@”符号时,下拉自动完成建议会显示api调用中的所有用户。只是想知道如果编写“@”符号,我将如何检查编辑文本。
谢谢!
答案 0 :(得分:1)
Android提供AutocompleteTextView小部件。使用此小部件而不是EditText并覆盖其标记器。
AutoCompleteTextView autoComplete = (AutoCompleteTextView)findViewById(R.id.autoCompleteId);
//Create a new Tokenizer which will get text after '@' and terminate on ' '
autoComplete.setTokenizer(new Tokenizer() {
@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 + " ";
}
}
}
@Override
public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;
while (i > 0 && text.charAt(i - 1) != '@') {
i--;
}
//Check if token really started with @, else we don't have a valid token
if (i < 1 || text.charAt(i - 1) != '@') {
return cursor;
}
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;
}
});
答案 1 :(得分:0)