Android 和 CommaTokenizer
我需要一个 Tokenizer(用于 AutoCompleteTextview),它可以执行以下操作:
- 当由空白字符分隔时,两个单词必须被识别为这样
- 当由换行符分隔时,两个单词也必须被识别为这样(按下“Enter”)
1)是工作,但我怎样才能完成2?
public class SpaceTokenizer implements 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) == ' ' || text.charAt(i) == '\n')) {
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) == ' ' || text.charAt(i) == '\n') {
return i;
} else {
i++;
}
}
return len;
}
@Override
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && (text.charAt(i - 1) == ' ' || text.charAt(i - 1) == '\n')) {
i--;
}
if (i > 0 && (text.charAt(i - 1) == ' ' || text.charAt(i - 1) == '\n')) {
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 + " ";
}
}
}
}
I need a Tokenizer (for the AutoCompleteTextview) which can do the following:
- Two words must be recognized as such when separated by a blank character
- Two words must also be recognized as such when separated by a newline ("Enter" pressed)
1) is working, but how can I accomplish 2?
public class SpaceTokenizer implements 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) == ' ' || text.charAt(i) == '\n')) {
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) == ' ' || text.charAt(i) == '\n') {
return i;
} else {
i++;
}
}
return len;
}
@Override
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && (text.charAt(i - 1) == ' ' || text.charAt(i - 1) == '\n')) {
i--;
}
if (i > 0 && (text.charAt(i - 1) == ' ' || text.charAt(i - 1) == '\n')) {
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 + " ";
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够执行此操作:
text.charAt(i) == ' ' || text.charAt(i) == '\n'
或i-1
(如果适用)。You should be able to do this:
text.charAt(i) == ' ' || text.charAt(i) == '\n'
ori-1
where appropriate.这是任何感兴趣的人的完整代码,也必须在我自己的应用程序中实现这一点。感谢@Haphazard 的回答。
Here is the whole code for anyone that is interested, had to implement this also in my own app. Thanks to answer from @Haphazard.