Android SetColorFilter()与SetBackgroundResource()/ SetColorBackground()

时间:2013-02-21 18:27:44

标签: android android-edittext background-color

任何人都可以解释这种外观上的差异吗? SetColorFilter()作用于Drawable背景,无论setBackgroundResource()设置背景颜色。
在Android 2.3版中,我安全地使用SetColorFilter()来改变EditText的背景颜色,因为通过清除过滤器很容易恢复原始颜色。无需记住它。现在两种方式之间似乎存在差异。

这是一个EditTextPreference对话框,et是EditText id。

        public void afterTextChanged(Editable s) {
            String source = s.toString();
            et.removeTextChangedListener(this);
            if( !source.matches("^[0-9]+$") ) {
                et.getBackground().setColorFilter(getResources().getColor(R.color.invalid), Mode.OVERLAY);
                et.invalidate();
                et.selectAll();
            } else {
                et.getBackground().clearColorFilter();
                et.invalidate();
            }
            et.addTextChangedListener(this);
        }

enter image description here

这是使用SetBackgroundResource()

的相同代码
        public void afterTextChanged(Editable s) {
            String source = s.toString();
            et.removeTextChangedListener(this);
            if( !source.matches("^[0-9]+$") ) {
                et.setBackgroundResource(R.color.invalid);
                et.selectAll();
            } else {
                et.setBackgroundResource(R.color.valid);
            }
            et.addTextChangedListener(this);
        }

enter image description here

1 个答案:

答案 0 :(得分:0)

如上所述,您可以使用textView.setError("Error message")。 如果你想自定义setError()的行为(比如改变背景颜色),你很遗憾地需要覆盖EditText并为setError编写自己的处理程序,如下所示:EditText setError() with icon but without Popup message