银行卡号四位分割

@ 银行卡号四位分割

public class BankFormatWatcher implements TextWatcher {
private EditText currentEt;

public BankFormatWatcher(EditText currentEt) {
    this.currentEt = currentEt;
}

@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 == null) {
        return;
    }
    //判断是否是在中间输入,需要重新计算
    boolean isMiddle = (start + count) < (s.length());
    //在末尾输入时,是否需要加入空格
    boolean isNeedSpace = false;
    if (!isMiddle && s.length() > 0 && s.length() % 5 == 0) {
        isNeedSpace = true;
    }
    if (isMiddle || isNeedSpace) {
        currentEt.removeTextChangedListener(this);
        String newStr = formatBankNum(s.toString());
        currentEt.setText(newStr);
        //如果是在末尾的话,或者加入的字符个数大于零的话(输入或者粘贴)
        if (!isMiddle || count > 1) {
            currentEt.setSelection(newStr.length());
        } else {
            //如果是删除
            if (count == 0) {
                //如果删除时,光标停留在空格的前面,光标则要往前移一位
                if ((start - before + 1) % 5 == 0) {
                    currentEt.setSelection((start - before) > 0 ? start - before : 0);
                } else {
                    currentEt.setSelection((start - before + 1) > newStr.length() ? newStr.length() : (start - before + 1));
                }
            }
            //如果是增加
            else {
                if ((start - before + count) % 5 == 0) {
                    currentEt.setSelection((start + count - before + 1) < newStr.length() ? (start + count - before + 1) : newStr.length());
                } else {
                    currentEt.setSelection(start + count - before);
                }
            }
        }
        currentEt.addTextChangedListener(this);
    }
}

@Override
public void afterTextChanged(Editable s) {

}

public static String formatBankNum(String source) {
    return source.replaceAll(" ", "").replaceAll("\\d{4}(?!$|\\s)", "$0 ");
}}

拿过去就可以用

猜你喜欢

转载自blog.csdn.net/w517272812/article/details/88568799
0条评论
添加一条新回复