Counting Chars in EditText Changed Listener


Question

In my project I have an EditText. I want to count the characters in the EditText, and show that number it in a TextView. I have written the following code and it works fine. However, my problem is when I click Backspace it counts up, but I need to decrement the number. How can I consider Backspace?

tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        i++;
        tv.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){}
}); 
1
272
9/8/2015 5:50:49 AM

Accepted Answer

Use

s.length()

The following was once suggested in one of the answers, but its very inefficient

textMessage.getText().toString().length()
142
12/19/2014 4:19:19 PM

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon