使用TextWatcher时,退格键无法正常工作

时间:2019-08-08 19:57:28

标签: android android-edittext textwatcher backspace

我需要格式化输入到EditText中的货币值,所以我使用了TextWatcher,但是现在我在软键盘上有退格键。

通常,如果您按住键盘上的退格键键,它会{strong>继续删除EditText中的字符,直到没有剩余字符为止。添加TextWatcher之后,您需要手动按退格键很多次,以完全摆脱所有字符,因为不再按住它有效

如何解决?

public class NumberTextWatcher implements TextWatcher {
    private final EditText et;

    public NumberTextWatcher(EditText et) {
        this.et = et;
    }

    @Override
    public void afterTextChanged(Editable s) {
        et.removeTextChangedListener(this);

        try {
            String originalString = s.toString();

            long longval;
            if (originalString.contains(",")) {
                originalString = originalString.replaceAll(",", "");
            }
            longval = Long.parseLong(originalString);

            DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            formatter.applyPattern("#,###,###,###");
            String formattedString = formatter.format(longval);

            //setting text after format to EditText
            et.setText(formattedString);
            et.setSelection(et.getText().length());
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }

        et.addTextChangedListener(this);
    }

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

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

    }
}

1 个答案:

答案 0 :(得分:0)

根据afterTextChanged(Editeable s)文档,在此EditText上发生的任何更改都会从此回调中得到通知,并且很明显,此回调锁定了退格,以便在您重新格式化文本时获得优势需要"#,###,###,###"

错误修复程序::您需要继续执行代码only and only if the input wasn't the backspace key,即:

   @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (after < count) {
            isBackspaceClicked = true;
        } else {
            isBackspaceClicked = false;
        }
    }

  @Override
    public void afterTextChanged(Editable s) {
        if (!isBackspaceClicked) {
            // Your current code
        }
     }