0

I am trying to automatically place a decimal two places in when the user begins to type in an EditText. The problem is I'm trying to set the TextWatcher on the EditText that I'm working with so when it updates the text in the field it recursively calls the method again. I'm getting an infinite loop. Here is what I've tried:

mTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mTime.removeTextChangedListener(this);
                if(mTime.getText().length() > 2){
                    double amount = Double.valueOf(mTime.getText().toString());
                    amount /= 100.0;
                } 
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mTime.addTextChangedListener(this);
            }

mTime is the EditText's name. My thinking was that once I triggered onTextChanged, I would remove the TextChangedListener, update the EditText and then re-instate the TextChangedListener in afterTextChanged. Unfortunately this didn't work. Any ideas or help would be appreciated.

This should be an easy task. I guess I'm just missing it

Jo Momma
  • 1,126
  • 15
  • 31

1 Answers1

0

you have pretty much right just make few changes below to your code:

 mTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mTime.removeTextChangedListener(this);
                if(mTime.getText().length() > 2){
                    double amount = Double.valueOf(mTime.getText().toString());
                    amount /= 100.0;
                } 
                mTime.addTextChangedListener(this);
            }
vikas kumar
  • 10,447
  • 2
  • 46
  • 52