TextWatcher in Android

290 views Asked by At

I have an EditText having a maximum supporting character of 10. What i want is when i type the count should decrement and on backspace the count should increment.....

private static TextView messageCount=null;
messageCount=(TextView) findViewById(R.id.messageCount);

mMessageField.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(count>0)
            {
                count--;
                messageCount.setText("Count=>"+count);
                //Toast.makeText(mContext, "Count=>"+count, Toast.LENGTH_LONG).show();
            }               
        }
    });
3

There are 3 answers

4
Anand Singh On BEST ANSWER

Try something like this:

 @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    int count1 = 10 - mMessageField.getText().toString().length();
    messageCount.setText("Count=>"+String.valueOf(count1));

    }

it will tell you length of textview. Put this inside "onTextChanged" so by doing so length will increase or decrease according to text you enter or delete.

2
Vatsal Shah On

Please check the below updated code.

private static TextView messageCount=null;
messageCount=(TextView) findViewById(R.id.messageCount);

mMessageField.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(mMessageField.getText().toString().length <=10)
            {
                 if(count>0)
            {
               count =  10 - mMessageField.getText().toString().length();
                messageCount.setText("Count=>"+count);
                //Toast.makeText(mContext, "Count=>"+count, Toast.LENGTH_LONG).show();
            }          
            }else{
Toast.makeText(mContext, "You can enter maximum 10 character", Toast.LENGTH_LONG).show();

        }
    });

Let me know if it will help you.

0
JozeRi On

Sadly, to the best of my knowledge, a Backspace on the soft keyboard is not an Event you can catch or react to.

the best possible way I can think of is to create an integer value that saves the current text length on your "afterTextChanged".

then, every time you get to afterTextChanged you compare the new value to the old one, if its value is lower then the previous value then you pressed backspace, if it's larger then the user probably typed a key.