I can disable EditText
, but then the user will simply unable to change the text. The behaviour I am trying to implement is that, if the user tries to type something (or any other changing method such as pasting), showing a message like "You cannot edit this text because of something.".
At first, I thought I could show the message using TextWatcher
, but there seems to be no way to cancel the change. How can I achieve the behaviour I am looking for? The only way I could think is the following really dirty way.
Have a backup of the text of the EditText. When EditText is changed, if
isReverting
is false, show the message and setisReverting
to true. IfisReverting
is true, just set it to false. Set the backup to the EditText.
A TextWatcher
will fullfill the need in your case . Do the validation inside afterTextChange()
. Below is an example.
et_Name.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 input=s.toString();
if(s.length()>4){
Toast.makeText(MainActivity.this, "You can only input 4 letters",
Toast.LENGTH_SHORT).show();
String old=input.substring(0,4);
et_Name.setText(old);
et_Name.setSelection(old.length());
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With