在 Android 源码中,MultiAutoCompleteTextView 类里面自带了一个静态的 CommaTokenizer 内部类去实现静态的 Tokenizer 接口,分别将 Tokenizer 接口里面的三个方法都实现出来。CommaTokenizer 对象的作用是两个列表项之间用一个逗号分隔开。如果你不想使用逗号分隔两个列表项,你可以自定义 Tokenizer(在这我使用的是以 ";" 分号分隔的),代码如下:
// 在一个类里面定义的一个静态的内部类(假如这个静态内部类在 TextInputActivity 类里面)。
public static class SemicolonTokenizer implements Tokenizer
{
//第一个方法
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;
}
//第二个方法
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;
}
//第三个方法
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 + "; ";
}
}
}
}
最后,可以通过
MultiAutoCompleteTextView mtext =
(MultiAutoCompleteTextView)findViewById(R.id.MultiAutoCompleteTextView01);
mtext.setAdapter(adapter);
mtext.setTokenizer(new TextInputActivity.SemicolonTokenizer());