【问题标题】:Backspace doesn't work properly when TextWatcher is used使用 TextWatcher 时退格无法正常工作
【发布时间】:2019-12-16 14:07:30
【问题描述】:

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

通常,如果您按住键盘上的退格键,它会继续删除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) {

    }
}

【问题讨论】:

    标签: android android-edittext textwatcher backspace


    【解决方案1】:

    根据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
            }
         }
    

    【讨论】:

    • 这如何回答这个问题?那么解决方法是什么?
    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    相关资源
    最近更新 更多