Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setCompoundDrawablesWithIntrinsicBounds is not working properly

I've an email field as EditText. I'm trying to add a green-tick icon at the end of the text field when the validation is true, and setError when it is false.

Here's the piece of code I'm using right now:

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);
                }
            }
        }
    });

PROBLEM:

Though I can see the log Yay: Email is valid!!!, it seems no icon is set as I can't see it. But when I change the if-condition to false, which means setError will never be called, I can see the log as well as the icon.

Any explanations upon why I'm seeing this strange behavior? What am I missing?

like image 484
Akeshwar Jha Avatar asked Jan 22 '16 10:01

Akeshwar Jha


2 Answers

try removing the icon from xml if you are setting any and set both images from the code for some reason the image does not refresh if you set one from xml

and use

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
          numTxt.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
    } else {    
          numTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
    }
like image 94
Hala.M Avatar answered Oct 22 '22 16:10

Hala.M


I am not sure if this is a bug but I am able to workaround this by setting the drawable to zero (0) first before assigning the new drawable.

In your case, you can try the following:

Log.i("YaY","Email is valid!!!");
email.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
email.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.validated, 0);
like image 33
ahdzlee Avatar answered Oct 22 '22 16:10

ahdzlee