加入onTextChanged后实行清晰的文本的EditText文本、清晰、onTextChanged、EditText

2023-09-07 15:25:35 作者:宽带你的世界。

我加入一个监听到一个EditText现场实时数相应地格式化货币。

I'm adding a listener to an EditText field to appropriately format the number to currency in real time.

        loanText.addTextChangedListener(new TextWatcher() {
        private String current = "";
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!s.toString().equals(current)){
               String cleanString = s.toString().replaceAll("[$,.]", "");

               double parsed = Double.parseDouble(cleanString);
               String formated = NumberFormat.getCurrencyInstance().format((parsed/100));

               current = formated;
               loanText.setText(formated);
               loanText.setSelection(formated.length());
            }
        }
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }
    });

然而,当我尝试清除EditView中外地,我的应用程序会崩溃。此外,退格键不再起作用。

However, when I try to clear the EditView field, my App will crash. In addition, the backspace key no longer functions.

推荐答案

的问题是,你的 TextWatcher 认为你是清算的文本,因此将关闭其回调方法的要求( afterTextChanged beforeTextChanged 等)。

The problem is that your TextWatcher sees that you are "clearing" the text, and therefore sends off a request to its callback methods(afterTextChanged, beforeTextChanged, etc).

我做了什么是简单地删除 TextWatcher ,清除文本,并添加 TextWatcher 回在的EditText 。这样一来,没有什么是听我的的EditText 的变化。

What i've done is to simply remove the TextWatcher, clear the text, and add the TextWatcherback to the EditText. That way, nothing is listening to my EditText changes.

您可能必须坚持以 TextWatcher 的内联,而不是像你做一个实例。这样,你就不必创建一个要清除每次的EditText

You will probably have to hold on to an instance of the TextWatcher instead of inlining it like you did. That way you don't have to create one every time you want to clear the EditText

loanText.removeTextChangedListener(yourTextWatcherObject); loanText.setText(); loanText.addTextChangedListener(yourTextWatcherObject); loanText.removeTextChangedListener(yourTextWatcherObject); loanText.setText(""); loanText.addTextChangedListener(yourTextWatcherObject);