当货币等于 0 时,使用 TextWatcher 删除 EditText 的值

Remove value of EditText with TextWatcher when the currency is equals to 0

我正在尝试在值等于 R[=13=],00 时清理 EditText

我尝试做的是使用 edittext.clear(); 清除文本但没有成功,并且使用 valor.removeTextChangedListener(new Ferramentas.EditValor(valor)); 也没有改变任何事情,那么我该怎么做呢?

public static class EditValor implements TextWatcher {

        private String current = "";
        private EditText valor;


        public EditValor(EditText text){
            this.valor = text;
        }

        @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) {
            if (!s.toString().equals(current)) {

                current = valorMoeda(s.toString());
                valor.setText(valorMoeda(s.toString()));
                valor.setSelection(valorMoeda(s.toString()).length());
            }

        }
    }

ValorMoeda:

public static String valorMoeda(String s) {


        String replaceable = String.format("[%s,.\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
        String cleanString = s.replaceAll(replaceable, "");

        double parsed;
        try {
            parsed = Double.parseDouble(cleanString);
        } catch (NumberFormatException e) {
            parsed = 0.00;
        }
        String formatted = NumberFormat.getCurrencyInstance().format((parsed / 100));


        return formatted;
    }

您可以使用afterTextChanged()方法清除您的文本,例如:

 yourEditText.addTextChangedListener(new TextWatcher() {
        @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) {

          if("R[=10=],00".equals(s.toString())){
             yourEditText.setText(""); // or yourEditText.getText().clear();
          }

        }

});

更新:

试试这个代码:

    @Override
    public void afterTextChanged(Editable s) {

         String newString = s.toString();

         if (newString.length>0 && !newString.equals(current)) {

            String newFormattedValue = valorMoeda(s.toString());

            if("R[=11=],00".equals(newFormattedValue)){
               valor.setText("");
            } else {
               current = newFormattedValue;
               valor.setText(newFormattedValue);
               valor.setSelection(newFormattedValue.length());
            }
        }
    }