Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel text change of EditText after showing a message?

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 set isReverting to true. If isReverting is true, just set it to false. Set the backup to the EditText.

like image 384
Damn Vegetables Avatar asked Oct 16 '22 18:10

Damn Vegetables


1 Answers

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());
            }
        }
    });
like image 139
ADM Avatar answered Oct 20 '22 22:10

ADM