AZ_ AZ_ - 1 year ago 114
Android Question

Android How to set maximum "word" limit on EditText

How to set maximum word limit on Android

I know how to set character limit but I am looking for Word Limit.

Answer Source

You need to add a TextChangedListener to your EditText then apply an InputFilter see the following code.

edDesc.addTextChangedListener(new TextWatcher() {

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

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        int wordsLength = countWords(s.toString());// words.length;
        // count == 0 means a new word is going to start
        if (count == 0 && wordsLength >= MAX_WORDS) {
            setCharLimit(edDesc, edDesc.getText().length());
        } else {

        tvWordCount.setText(String.valueOf(wordsLength) + "/" + MAX_WORDS);

    public void afterTextChanged(Editable s) {}

private int countWords(String s) {
    String trim = s.trim();
    if (trim.isEmpty())
        return 0;
    return trim.split("\\s+").length; // separate string around spaces

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;

You have to intercept Paste event so that user shouldn't be able to paste more than required words. You can intercept Android EditText Paste event [read more]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download