I am trying to limit an edit text of one character, I have a CustomTextWatcher class which handle all text changes events. Lets say if i write one letter, the focus will automatically jump to the next edit text, but if I touch on the editText to getFocus if cursor is before previous letter it allows me to write one letter being 2 then, i tried clearing edit text in beforeTextChanged but it crashes the app, any ideas of how to approach this problem?
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
EditText e = (EditText) v;
if(e.getText().toString().length() == 0 || e.getText().toString().equals(""))
e.setText(s); // if true means there is no previous text so i can just use whatever comes in s charSequence
else
e.setText(""); // if false, means there is some text, so i want to clean it up first and write new character
Log.d(TAG, "beforeTextChanged: ");
}
UPDATE : ok so after following the recomendations this is what I've got:
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
hasToClear = false;
e = (EditText) v;
if(e.getText().toString().length() > 0 || !e.getText().toString().equals("")) {
previousChar = e.getText().toString(); // if either true, the box was not empty
hasToClear = true;
}
Log.d(TAG, "beforeTextChanged: ");
}
@Override
public void afterTextChanged(Editable s) {
InputFilter[] editFilters = s.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 2];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.AllCaps();
if(!isNumber)
newFilters[editFilters.length+1] = charFilter;
else
newFilters[editFilters.length + 1] = digitFilter;
s.setFilters(newFilters);
if(isAllowed) {
if (i == NUM_DIGITS) {
edList[5].clearFocus();
onTextFinishedListener.onPlateFinished(true);
} else {
edList[i].selectAll();
edList[i].requestFocus();
}
}
String stringToReplace = "";
if(previousChar != null) { // find which caracter is diferent as there is only one allowed
for (int x = 0; x < s.length(); x++) {
if (s.charAt(x) != previousChar.charAt(0)) {
stringToReplace = String.valueOf(s.charAt(x));
break;
} else stringToReplace = String.valueOf(previousChar);
}
}
if(hasToClear){ // if true clear
e.removeTextChangedListener(this);
e.setText("");
e.setText(stringToReplace);
e.addTextChangedListener(this);
}
}
if user clicks on, before or after any character the next input user does, must replace to previous character, this is happening with before and on character, but is not happening with after
From the docs of
beforeTextChanged
:Hence you should move the same code to
afterTextChanged
where it is legal to make changes to theEditText
.Note: If you are setting text in
afterTextChanged
on the sameEditText
then theTextWatcher
will be fired. If this is not intended behaviour, should remove the TextWatcher, set the text and then add the TextWatcher back.