1

In EditText where I want to add a letter counter. it counts properly but when I entered backspace it's also considered as a letter and count added by 1 which actually should be decremented by 1. my code is

text_feedback_text.addTextChangedListener(new TextWatcher()
        {
            public void afterTextChanged(Editable s) 
            {
                                int keyCode = 0;
                if(keyCode==KeyEvent.KEYCODE_DEL){
                    i--;
                    Log.d("back","backspace pressed"+i);
                }else 
                    i++;
                text_feedback_count.setText(String.valueOf(i) + " / " + String.valueOf(charCounts));
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                text_feedback_count.setText(String.valueOf(s.length()));
            }
        } 
        );

Please help me out when i clicking backspace its not detecting and also not printing on logcat.

Please reply if anybody have some clue.

Thank you!

Elin
  • 6,507
  • 3
  • 25
  • 47
Abhishek Karande
  • 377
  • 3
  • 10
  • 19
  • 8
    1. TextWatcher is for watching text. 2. seems like you do not understand your own code : you assing 0 to keyCode `int keyCode = 0;` and then compare it to `KeyEvent.KEYCODE_DEL` ... i'm pretty sure that `KeyEvent.KEYCODE_DEL != 0` ... so `i--;` is never called ... – Selvin Feb 27 '12 at 14:04
  • @Abhishek Karande also if we enter space then also TextWatcher listener not working...any help here? – CoDe Jan 12 '13 at 11:29
  • http://stackoverflow.com/questions/12202047/detect-backspace-in-textwatcher – Damir Mailybayev Dec 26 '16 at 06:34

1 Answers1

0

use OnKeyListener for you editText so you can detect any key press

editText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
           if(keyCode == KeyEvent.KEYCODE_DEL){  
             //Control comes here when backspace is clicked
             }
    return false        
        }
});
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243