Android EditText输入一串字符串自动每4个字符空一格,像输入银行卡卡号格式

来源:互联网 发布:开放源代码软件 编辑:程序博客网 时间:2024/05/16 13:55

  最近写类似需要像银行卡输入那样每4个字符空一格,网上看了很多都没有很好的解决索性自己写一个。主要思路就是活用beforeTextChanged()、onTextChanged()、afterTextChange()。代码测试过没有问题,可以在字符串中间任意位置添加删除字符。中间难点是光标位置,其实只是添加删除字符是没什么难度的。代码如下,贴出来方便以后自己查看~


String beforeStr = "";    String afterStr = "";    String changeStr = "";    int index = 0;    boolean changeIndex = true;    public void initListener() {        et.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {                beforeStr = s.toString();            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {                afterStr = s.toString();                if (changeIndex)                    index = et.getSelectionStart();            }            @Override            public void afterTextChanged(Editable s) {                if ("".equals(s.toString()) || s.toString() == null || beforeStr.equals(afterStr)) {                    changeIndex = true;                    return;                }                changeIndex = false;                char c[] = s.toString().replace(" ", "").toCharArray();                changeStr = "";                for (int i = 0; i < c.length; i++) {                    changeStr = changeStr + c[i] + ((i + 1) % 4 == 0 && i + 1 != c.length ? " " : "");                }                if (afterStr.length() > beforeStr.length()) {                    if (changeStr.length() == index + 1) {                        index = changeStr.length() - afterStr.length() + index;                    }                    if (index % 5 == 0 && changeStr.length() > index + 1) {                        index++;                    }                } else if (afterStr.length() < beforeStr.length()) {                    if ((index + 1) % 5 == 0 && index > 0 && changeStr.length() > index + 1) {                        //  index--;                    } else {                        index = changeStr.length() - afterStr.length() + index;                        if (afterStr.length() % 5 == 0 && changeStr.length() > index + 1) {                            index++;                        }                    }                }                et.setText(changeStr);                et.setSelection(index);            }        });    }
其中et是EditText控件~

1 0