本文介绍了setCompoundDrawablesWithIntrinsicBounds无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的电子邮件字段为EditText.验证为true时,我试图在文本字段的末尾添加一个绿色的勾号图标;为false时,我为setError添加一个绿色的勾号.

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

问题:

尽管我可以看到日志Yay: Email is valid!!!,但似乎没有设置图标,因为我看不到它.但是,当我将if-condition更改为false时,这意味着将永远不会调用setError,我可以看到日志以及图标.

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?

推荐答案

如果要设置xml,请尝试从xml中删除图标并从代码中设置两个图像由于某些原因,如果您从xml设置图片,图片不会刷新

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

并使用

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

这篇关于setCompoundDrawablesWithIntrinsicBounds无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:49