java - 格式化 TextWatcher android

标签 java android regex android-edittext android-textwatcher

我的 FourDigitCardFormatWatcher 每 4 个数字后添加一个空格。我想将 FourDigitCardFormatWatch 更改为以下格式 55555 5555 555 55。

如何确定5位数字后加空格,4位数字后加空格,3位数字后加空格。

实际结果:4444 4444 4444

预期结果:44444 4444 444

最佳答案

像这样编辑类..

public class FourDigitCardFormatWatcher implements TextWatcher {

// Change this to what you want... ' ', '-' etc..
private final String char = " ";
EditText et_filed;


public FourDigitCardFormatWatcher(EditText et_filed){
    this.et_filed = et_filed;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void afterTextChanged(Editable s) {
    String initial = s.toString();
    // remove all non-digits characters
    String processed = initial.replaceAll("\\D", "");

    // insert a space after all groups of 4 digits that are followed by another digit
    processed = processed.replaceAll("(\\d{5})(\\d{4})(\\d{3})(?=\\d)(?=\\d)(?=\\d)", "$1 $2 $3 ");

    //Remove the listener
    et_filed.removeTextChangedListener(this);

    //Assign processed text
    et_filed.setText(processed);

    try {
        et_filed.setSelection(processed.length());
    } catch (Exception e) {
        // TODO: handle exception
    }

    //Give back the listener
    et_filed.addTextChangedListener(this);
}
}

添加监听器

editText1.addTextChangedListener(new FourDigitCardFormatWatcher(editText1));

关于java - 格式化 TextWatcher android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341857/

相关文章:

android - 在不同屏幕的背景图像上将按钮定位在固定位置?

Python 正则表达式 : Ignore Escaped Character

python - 匹配具有交替字符的字符串

Python:从正则表达式中排除空格

java - Java中的简单游戏网络引擎/library/API?

java - 使用 axis2 和 apache 的网络服务连接

java - Hibernate:插入ManyToMany,在关系表中生成ID

android - 如何在不重新启动 Activity 的情况下在android中应用主题/样式?

android - 使用 FileProvider Android 从可移动 SD 卡打开文件时出错

java 。 InetAddress.getLocalHost 返回奇怪的 IP