当前位置: 移动技术网 > IT编程>移动开发>Android > EditText超出字数限制,给用户提示

EditText超出字数限制,给用户提示

2018年09月14日  | 移动技术网IT编程  | 我要评论

新安人才网,星河舰队4,as798.tk

当我们在editext输入内容的时候,检测如果超过限制的长度无法输入内容,并且给用户提示。

首先我想到了下面的方法:

 edittext.addtextchangedlistener(new textwatcher() {
            @override
            public void beforetextchanged(charsequence s, int start, int count, int after) {
            }

            @override
            public void ontextchanged(charsequence s, int start, int before, int count) {
                if (s.length() > 6){ //判断edittext中输入的字符数是不是已经大于6
                    edittext.settext(s.tostring().substring(0,6)); //设置edittext只显示前面6位字符
                    edittext.setselection(6);//让光标移至末端
                    toast.maketext(mainactivity.this, "输入字数已达上限", 
toast.length_short).show(); return; } } @override public void aftertextchanged(editable s) { } });

未经测试,个人觉得这种体验或许不是很好,或许会出现editext闪动。

 

其实我们可以用下面这种方法:

源码给editext设置了过滤器,专门用来判断是否超出最大的字符长度,把这段过滤器取出来,在里面加上toast提示,设置给editext就可以了。

  class mylengthfilter implements inputfilter {

        private final int mmax;
        private context context;

        public mylengthfilter(int max, context context) {
            mmax = max;
            this.context = context;
        }

        public charsequence filter(charsequence source, int start, int end, spanned dest,
                                   int dstart, int dend) {
            int keep = mmax - (dest.length() - (dend - dstart));
            if (keep <= 0) {
                //这里,用来给用户提示
                toast.maketext(context, "字数不能超过" + mmax, toast.length_short).show();
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (character.ishighsurrogate(source.charat(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subsequence(start, keep);
            }
        }

        /**
         * @return the maximum length enforced by this input filter
         */
        public int getmax() {
            return mmax;
        }
    }

调用:

meditext.setfilters(new inputfilter[]{new mylengthfilter(100,context)});      

 

源码中该方法是这样的:

public void setfilters(inputfilter[] filters) {
        if (filters == null) {
            throw new illegalargumentexception();
        }

        mfilters = filters;

        if (mtext instanceof editable) {
            setfilters((editable) mtext, filters);
        }
    }

由此可见我们可以给editext设置多个过滤器,例如过滤掉一些特殊字符,表情等等。

 

学习android有一个很重要的能力就是阅读源码的能力,很多问题都可以通过阅读源码找到解决方法。

参考链接:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网