-1

I am trying to get the Dynamic Or Live word count for an Edit Text. To explain the problem, I have an EditText and a Textview inside a fragment, whenever the user enters a sentence in the EditText it should automatically count the number of words occurring in that sentence and display the number of words in the TextView.

I have implemented the Text Watcher but can't figure out the code snippet.

Any help will be appreciated.

Sumit Roy
  • 63
  • 1
  • 3
  • 9

1 Answers1

0

One of the callbacks of a TextWatcher is afterTextChanged(Editable edit).

A Editable is what you get when you call getText on an EditText, which holds the current text, and therefore also knows the length of the current text.

So you can do something like this:

        editText.addTextChangedListener(new TextWatcher() {
            ...
            @Override
            public void afterTextChanged(Editable editable) {
                String currentText = editable.toString();
                int currentLength = currentText.length();
                textView.setText("Current length: " + currentLength);
            }
        });
Moonbloom
  • 7,738
  • 3
  • 26
  • 38
  • 1
    this code is returning the count of number of characters, I need the count of number of words entered in the editText.. – Sumit Roy May 18 '17 at 18:47
  • Then split the currentText with a space and use .length on the returned array. That's how many words there are in the entire text. – Moonbloom May 18 '17 at 18:58
  • It's NOT working when you have single words separated by returns. – Martinocom Oct 28 '17 at 12:46