关于EDITTEXT的监听,以及限制特定字节数的实现

来源:互联网 发布:捰体p图软件 编辑:程序博客网 时间:2024/05/16 01:29

首先这个问题,纠结了半天,测试提了个bug,说可编辑框需要限制特定的字节个数。我想怎么办呢,先是说android不能实现,应付了过去,最后经过一想,ios可以实现,android 应该也可以实现。于是在网上各种寻找,最后功夫不负有心人,终于找到了。

其实现方式是通过edittext的监听,TextWatcher。

需要在文本改变之后的回调中afterTextChanged(Editable s),进行重新修改。这里利用Editable的功能方法(太基础了),我竟然不会。

比如这里限制30个字节,我们知道中文3个字节,英文1个字节,所以这里需要用到正则表达式规则来限制这个个数string.replaceAll("[^\\x00-\\xff]", "**").length()来表示,具体什么含义,自己去学习正则表达式的各种语法,我学习了半天这个。

之后就是Editable的用法了,以及如何使用光标了。

条件:

1:两边的空格不考虑进来

2:中间的空格考虑


具体实现:

            private int selectionStart ;
            private int selectionEnd ;

@Override
            public void afterTextChanged(Editable s) {
                switchHint(s);
                
                selectionStart = real_name.getSelectionStart();
                selectionEnd = real_name.getSelectionEnd();
                real_name.removeTextChangedListener(this);//防止内存溢出,必须写。
                
                while (s.toString().trim().replaceAll("[^\\x00-\\xff]", "**").length() > 30) {//循环到30个字节为止
                    s.delete(selectionStart - 1, selectionEnd);
                    selectionStart--;
                    selectionEnd--;
                }
                real_name.setText(s);//重新设置字符串
                real_name.setSelection(selectionStart);//重新设置光标的位置
                real_name.addTextChangedListener(this);//配合removeTextChangedListener
            }


其中,getSelectionStar 和getSelectionEnd是edittext的光标的起始位置和终止位置,这样一个看似很简单的bug,竟然耗了我一天,真的要说我的基础还需要提高。

0 0