About Android custom Tokenizer(use for MultiAutoCompleteTextView)

        在 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());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值