android 格式化EditText输入

项目中需要输入框自动将输入内容格式化为###.###.###-##
就需要对输入内容格式化后,重新调用EditText的setText方法设置格式化后的文本,不过处理关于光标的问题有点细节,关于用户在输入内容中间增加或删除字符后,光标就乱了,最开始处理所有的修改都将光标置于尾部,体验不太好,所以好好处理了下,大家看下有没有c、v的可能性吧。
在这里插入图片描述
其实就是记录根据发生变化的起始下标和增加的文本长度,根据0到起始下标+增加文本长度格式化重新计算下标 设置下标位置
talk is cheap,show code

etCpf.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        formatCpf(s.toString(), etCpf, start, count);
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});

private static final String CPF_PATTERN = "[0-9]{3}\\.+[0-9]{3}\\.+[0-9]{3}-+[0-9]{2}";

private static String formatCpf(String cpf, EditText editText, int start, int count) {
    if (Pattern.matches(CPF_PATTERN, cpf)) {
        return cpf;
    } else {
        String realCpf = cpf.replaceAll("-", "").replaceAll("\\.", "");
        StringBuilder sbCpf = new StringBuilder();
        if (realCpf.length() > 9) {
            sbCpf.append(realCpf, 0, 3)
                    .append(".")
                    .append(realCpf, 3, 6)
                    .append(".")
                    .append(realCpf, 6, 9)
                    .append("-")
                    .append(realCpf.substring(9));
        } else if (realCpf.length() > 6) {
            sbCpf.append(realCpf, 0, 3)
                    .append(".")
                    .append(realCpf, 3, 6)
                    .append(".")
                    .append(realCpf.substring(6));
        } else if (realCpf.length() > 3) {
            sbCpf.append(realCpf, 0, 3)
                    .append(".")
                    .append(realCpf.substring(3));
        } else {
            sbCpf.append(realCpf);
        }
        if (!TextUtils.equals(cpf, sbCpf.toString())) {
            editText.setText(sbCpf);
            String selectStr = cpf.substring(0, start + count).replaceAll("-", "").replaceAll("\\.", "");
            int selectIndex;
            if (selectStr.length() > 9) {
                selectIndex = selectStr.length() + 3;
            } else if (selectStr.length() > 6) {
                selectIndex = selectStr.length() + 2;
            } else if (selectStr.length() > 3) {
                selectIndex = selectStr.length() + 1;
            } else {
                selectIndex = selectStr.length();
            }
            if (selectIndex >= 0) {
                editText.setSelection(selectIndex);
            }
        }
        return sbCpf.toString();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 AndroidEditText 组件来输入数字,并设置输入类型为 "numberDecimal"。然后,在您的代码中,您可以使用 DecimalFormat 类来格式化输入,并确保它只显示两位小数。以下是一个简单的例子: 1. 在布局文件中设置 EditText 组件: ```xml <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" /> ``` 2. 在您的代码中获取 EditText 组件并设置格式化方式: ```java EditText editText = findViewById(R.id.editText); DecimalFormat decimalFormat = new DecimalFormat("#.##"); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // do nothing } @Override public void afterTextChanged(Editable s) { try { String input = s.toString(); if (!input.isEmpty()) { double value = Double.parseDouble(input); String formatted = decimalFormat.format(value); if (!input.equals(formatted)) { editText.setText(formatted); editText.setSelection(formatted.length()); } } } catch (NumberFormatException e) { // handle error } } }); ``` 此代码将监视 EditText 中的文本更改,并在用户输入后使用 DecimalFormat 将其格式化为两位小数。如果用户输入了无效的数字,则会捕获 NumberFormatException 异常并进行错误处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值