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.
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);
}
});