Android How to set maximum "word" limit on EditText
Asked Answered
G

4

10

How to set maximum word limit on Android EditText I know how to set character limit but I am looking for Word Limit.

Godsend answered 3/3, 2015 at 4:4 Comment(0)
G
18

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

edDesc.addTextChangedListener(new TextWatcher() {

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

    @Override
    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 {
            removeFilter(edDesc);
        }

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

    @Override
    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]

Godsend answered 3/3, 2015 at 4:4 Comment(3)
still you need to see for paste event :)Godsend
it fails when i have typed n words but want to change characters of an existing word. it won't let me type because of character limit filterBeaudette
this won't work for the last word, as soon as you add a character the editor won't let you add more charactersWhimwham
L
3

I have made Extension function for the EditText and it works perfectly

fun EditText.addWordCounter(func: (wordCount: Int?) -> Unit) {

addTextChangedListener(object :TextWatcher{
    override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val trim = s?.trim()
        val wordCount = if (trim?.isEmpty()!!or(false)) 0 else trim.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size

        func(wordCount)
    }
})}

then use like

etDesc.addWordCounter { wordCount ->
        Log.d(TAG, "addWordCounter: $wordCount")
    }
Leakage answered 23/1, 2019 at 9:40 Comment(0)
K
0

binding.etSectionDesc.doAfterTextChanged { val count = binding.etSectionDesc.content().wordCount()

        if (count >= ValidationConst.MAX_COURSE_DESC_LENGTH_SHOW) {
            setCharLimit(binding.etSectionDesc, binding.etSectionDesc.content().length)
        } else {
            removeFilter(binding.etSectionDesc)
        }

        binding.tvDescTotalChar.apply {
            text = count.toString()
            if (count < ValidationConst.MAX_COURSE_DESC_LENGTH_SHOW) {
                setTextColor(ContextCompat.getColor(context, R.color.black))
            } else {
                setTextColor(context.getAttrResource(R.attr.accentColor_Red))
            }
        }


    }
Krever answered 29/11, 2022 at 10:40 Comment(0)
B
-2

You can Limit the words to type in EditText.

Simply, add this

android:maxLength="10"

Full code:

 <EditText
        android:id="@+id/uname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:maxLength="10"/>

Official Documentation here

Happy Coding :)

Baudin answered 26/4, 2016 at 7:37 Comment(1)
That sets the maximum number of characters, not wordsTurco

© 2022 - 2024 — McMap. All rights reserved.