setCompoundDrawablesWithIntrinsicBounds is not working properly

怎甘沉沦 提交于 2020-01-14 12:31:51

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/34944012/setcompounddrawableswithintrinsicbounds-is-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!