How can we limit the EditText
length to certain number of word count (100 words).
Even though copy a large text from some where,while pasting it should accept only 100 words.
I know we can limit it by character count (maxLength
)
I tried with below code, but it doesn't limit it by exactly 100 words and it is allowing copy-paste large text.
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
int wordsLength = countWords(charSequence.toString());// words.length;
// count == 0 means a new word is going to start
if (count == 0 && wordsLength >= MAX_WORD_LIMIT) {
int charLength = mDescription.getText().length();
setCharLimit(mDescription, charLength > 0 ? charLength - 2 : charLength);
} else {
removeFilter(mDescription);
}
and
private InputFilter filter;
private void setCharLimit(EditText et, int max) {
filter = new InputFilter.LengthFilter(max);
et.setFilters(new InputFilter[]{filter});
}
private void removeFilter(EditText et) {
if (filter != null) {
et.setFilters(new InputFilter[0]);
filter = null;
}
}