Here I have an EditText which is prefilled with underscores. In the onTextChanged()-Method I replace the Underscores with the typed Letter. The Code is correct so far. Because I add and delete one Letter at the same Time I need to set the Selection to start+1 (marked in the Code with ----->). This Part of the Code causes the EditText to duplicate the letters. If I type abc, the EditText only shows aaa. If I select another Letter manually it will type the other letter, but duplicate the next one. If I delete et_xxx_opposite.setSelection(start + 1) it works, but the Selection replaces the same letter. The Code works with the Android Studio Emulator (SDK 33) and Xiaomi 11T Pro, but not with Samsung Galaxy Tab S6 Lite (SDK 33). Anyone have any Idea how i can reach the wanted behaviour on all devices?
final boolean[] userTyped = {false};
et_xxx_opposite.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) {
if (userTyped[0]) {
return;
}
userTyped[0] = true;
if (count >= 2) {
et_xxx_opposite.setText(xxx_opposite_hint.toString().trim());
} else {
if (start >= xxx_opposite.length() && s.toString().contains("_")) {
StringBuilder sb = new StringBuilder(s);
sb.delete(hisss_opposite.length(), s.length());
et_xxx_opposite.setText(sb.toString().trim());
et_xxx_opposite.setSelection(0);
} else {
if (count > before) {
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(start + 1);
et_xxx_opposite.setText(sb.toString());
------> et_xxx_opposite.setSelection(start + 1);
} else {
StringBuilder sb = new StringBuilder(s);
sb.insert(start, '_');
et_xxx_opposite.setText(sb.toString());
et_xxx_opposite.setSelection(start);
}
}
if (!et_xxx_opposite.getText().toString().contains("_")) {
et_xxx_opposite.setEnabled(false);
if (et_xxx_opposite.getText().toString().equalsIgnoreCase(hisss_opposite)) {
et_xxx_opposite.setTextColor(getResources().getColor(R.color.right, null));
} else {
et_xxx_opposite.setTextColor(getResources().getColor(R.color.wrong, null));
}
}
}
userTyped[0] = false;
}
@Override
public void afterTextChanged(Editable s) {
}
});