Android How to set maximum "word" limit on EditText

How to set maximum word limit on Android EditText I know how to set a character limit, but I'm looking for a word limit .

+6
source share
3 answers

You need to add a TextChangedListener to your EditText , and then apply an InputFilter to 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 need to catch the Paste event so that the user cannot insert more than the required words. You can intercept Android EditText Insert an event [read more]

+10
source

I made an extension function for EditText and it works great

 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().orFalse()) 0 else trim?.split("\\s+".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()?.size func(wordCount) } })} 

then use as

 etDesc.addWordCounter { wordCount -> Log.d(TAG, "addWordCounter: $wordCount") } 
0
source

You can limit the words to type in EditText.

Just 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"/> 

The official documentation is here

Happy coding :)

-2
source

Source: https://habr.com/ru/post/983245/


All Articles