The reason your code freezes is because onChangeListener
starts as soon as you setText
.
You need to find a way to stop the launch if the text is the same.
To do this, you can use the temp line to store the prev value and compare each time the event fires. This will maintain a constant flow, not a loop.
String prevString = "";
In afterTextChanged
String mNameStr = s.toString(); String finalStr = ""; if (!mNameStr.equals("")) { String[] strArray = mNameStr.split("[\\s']"); if (strArray.length > 0) { int i = 0; for (i = 0; i < strArray.length - 1; i++) { finalStr += capitalize(strArray[i]) + " "; } finalStr += capitalize(strArray[i]); Log.d("finalStr==> ", finalStr); } } if (!finalStr.equals(prevString)) { prevString = finalStr; editText.setText(finalStr.toString()); editText.setSelection(finalStr.length()); }
Optimization of your code consists only in using only a sentence if the last letter entered is after a space. You can see how this is implemented here.
editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String string = s.toString(); Log.d("STRING", string + " " + prevString); if (string.equals(prevString)) { return; } else if (string.length() == 0) return;
However, the procedure described above exists. This will not take into account the case when you change the position of the cursor and enter text.
PS: you can use the getSelectionEnd()
method and improve the method described above
source share