android - setCompoundDrawablesWithIntrinsicBounds 无法正常工作

标签 android android-edittext

我有一个电子邮件字段作为 EditText。我试图在验证为真时在文本字段的末尾添加一个绿色勾号图标,并在验证为假时添加 setError

这是我现在正在使用的一段代码:

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,我可以看到日志和图标.

关于为什么我会看到这种奇怪行为的任何解释?我错过了什么?

最佳答案

如果您正在设置任何图标,请尝试从 xml 中删除图标 并从代码中设置两个图像 由于某种原因,如果您从 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);
    }

关于android - setCompoundDrawablesWithIntrinsicBounds 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34944012/

相关文章:

android - 如何修复 UnsafeProtectedBroadcastReceiver?

android - 单击任何 EditText 时屏幕向上滚动

android - 如何使 Edittext 不可点击

android - 在 stripDebugDebugSymbols 步骤中找不到 arm-linux-androideabi 工具链

android - 如何为 alertDialog Box 创建通用类

android - 如何在 Intent 之间传递 bool 值

android - 等到 Text to Speech 开始说话

android - 无法从 EditText 获取 maxLength! (InputFilter.LengthFilter 没有长度参数,现在怎么办?)

android对editText设置限制,输入类型为 "date"

android - 如何允许粘贴到空的 EditText 中?