0

I have a problem with TextWatcher. After i am done editing, i want to append " kg" string. But after i try to edit editView, it loops and my app crashes. Can somebody help me? Thanks

weight = findViewById(R.id.editText);
        weight.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) {
                editable.append(" kg");
            }
        });

3 Answers3

2

You can manage this with an if statement but I think that it can down in better way

    weight.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable editable) {

            if(!editable.getText().contains("kg"))
               editable.append(" kg");
        }
    });
Mousa Jafari
  • 677
  • 1
  • 6
  • 21
  • 1
    With few changes your idea works good. I couldnt use editable, because it doesnt have getText method. I just changed editable with weight and it works. thank you – Christián Szeman Dec 18 '18 at 21:53
0

Its looping because setting the text calls afterTextChanged. What you could do is remove the text watcher, change the text, then re-add the text watcher.

Quinn
  • 7,072
  • 7
  • 39
  • 61
0

Follow these steps:

  1. Remove the TextWatcher temporarily
  2. Do your changes to your content
  3. Add the TextWatcher again

    weight.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) {
             if (editable.toString().contains("kg")) return
             weight.removeTextChangedListener(this);
             editable.append(" kg");
             weight.addTextChangedListener(this);
         }
     });
    
Oliver Metz
  • 2,712
  • 2
  • 20
  • 32