wawanopoulos
wawanopoulos

Reputation: 9794

Android : create count down word field when user type in EditText

I would like like to show in a TextView a counter which decrease following the number of character that the user write in an EditText.

I have one TextView to show the counter from 110 characters, 109, 108, 107 ....

wordCount = (TextView) findViewById(R.id.nouvelle_annonce_words_count) ;

And i have an Editext where the user write :

title = (EditText) findViewById(R.id.nouvelle_annonce_titre) ;

How can i listen the change in my EditText and update my textView with the number of character remaining ?

Upvotes: 1

Views: 546

Answers (2)

MrEngineer13
MrEngineer13

Reputation: 38856

What you're looking to do is called a TextWatcher

title.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            wordCount.setText(String.valueOf(110-s.length()));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

            // TODO Auto-generated method stub
        }
    });

Upvotes: 0

Matej Špilár
Matej Špilár

Reputation: 2687

you can use addTextChangedListener like this

title.addTextChangedListener(new TextWatcher() {

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
      wordCount.setText(String.valueOf(110 - (title.getText().toString().length)));
  }

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {

  }

  @Override
  public void afterTextChanged(Editable s) {

  }
});

Upvotes: 2

Related Questions