美文网首页
Android EditText 输入监听使用场景系列

Android EditText 输入监听使用场景系列

作者: 牧区叔叔 | 来源:发表于2021-02-03 13:05 被阅读0次

需求:注册界面输入手机号时候以188 8888 8888形式呈现
感谢博主:https://blog.csdn.net/as_csdn

实现效果:


手机输入.gif

实现EditText的TextWatcher接口即可,具体在深入研究

 et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                DLog.d("---------- beforeTextChanged ----------" + "\n");
                DLog.d("s: " + s + "\n");
                DLog.d("start: " + start + "\n");
                DLog.d("count: " + count + "\n");
                DLog.d("after: " + after + "\n");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                DLog.d("---------- onTextChanged ----------" + "\n");
                DLog.d("s: " + s + "\n");
                DLog.d("start: " + start + "\n");
                DLog.d("before: " + before + "\n");
                DLog.d("count: " + count + "\n");

                if (s==null||s.length()==0){
                    return;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i <s.length() ; i++) {
                    if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9)
                                && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    et_phone.setText(sb.toString());
                    et_phone.setSelection(index);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                DLog.d("---------- afterTextChanged ----------" + "\n");
                DLog.d("s: " + s + "\n");
            }
        });

后期在更新 相关.....

相关文章

网友评论

      本文标题:Android EditText 输入监听使用场景系列

      本文链接:https://www.haomeiwen.com/subject/qmdptltx.html