Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Validation symbol in EditText

We have the setError method for setting an error message with a red exclamation symbol at the end of the box if validation of an EditText returns false:

validation returned false

I want to set a green tick symbol, just like the red exclamation at the end of the box when my validation returns true:

password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {

                if (password.getText().toString().length() < 6) {
                    password.setError("Password should be greater than 6 characters!");
                }
                else {
                    //validation is true, so what to put here?
                }
            }
        }
    });
}

EDIT 1 Seemingly impossible, but there's more to the problem. I did this:

email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                String mail = email.getText().toString();
                if(!android.util.Patterns.EMAIL_ADDRESS.matcher(mail).matches()) {
                    email.setError("Please enter a valid email address");
                } 
                else {
                    Log.i("yay!","Email is valid!!!");
                    email.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.validated, 0);
                }
            }
        }
    });

Though I can see in my logs that yay: Email is valid!!!, I can't see the validation symbol at the end of the EditText.

However, to my surprise when I change the if statement to always false, I can see both the symbol with the log statement.

Any explanations upon why could this be happening?

like image 456
Akeshwar Jha Avatar asked Dec 05 '22 19:12

Akeshwar Jha


2 Answers

You can show drawableRight when your validation is true.

password.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.rightImage, 0);

and set it back to normal when validation is false.

password.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
like image 182
Ravi Avatar answered Dec 21 '22 08:12

Ravi


I just tested it out in my own project using setError(CharSequence error, Drawable icon)

  1. Get a new Icon:
    Go to my drawable folder
    adding a new vector asset.

    I picked "material icon" and browse,
    then picked ic_done_24pp.

  2. Color:
    Next, I went into the xml and made it green by changing the fillcolor:
    android:fillColor="#FF00FF00"

3: Change code:

Drawable myIcon = getResources().getDrawable(R.drawable.ic_done_24dp); 
myIcon.setBounds(0, 0, myIcon.getIntrinsicWidth(), myIcon.getIntrinsicHeight());
mPasswordView.setError("Good", myIcon); 

enter image description here

like image 29
Baronz Avatar answered Dec 21 '22 06:12

Baronz