通过编程方式更改一个EditText的颜色,可以改变整个应用程序中的EditText的颜色,使用的是Android 5版本。
通过编程方式更改一个EditText的颜色,可以改变整个应用程序中的EditText的颜色,使用的是Android 5版本。
在Android 5中,我遇到了一个非常奇怪的问题。如果用户输入错误,我想将错误信息设置到编辑框,并将其颜色改为红色;当用户开始输入时,我希望将颜色改回绿色。我是这样做的:
eText.setError(message); eText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); eText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { eText.getBackground().setColorFilter( ctx.getResources().getColor(R.color.dark_green), PorterDuff.Mode.SRC_ATOP); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) {} });
在低于Android 5的版本中,一切都运行得很完美,但在Lollipop中却不行。如果我改变了一个编辑框的颜色,所有应用程序中的所有编辑框都会改变颜色。有没有办法解决这个奇怪的问题?或者这是一些我不知道的材料设计和Android 5的技巧吗?
问题的原因是在Android Lollipop版本中,通过改变一个EditText的颜色,会导致整个应用中所有EditText的颜色都改变。解决方法是在代码中分别为KitKat版本和Lollipop版本实现不同的逻辑,对于Lollipop版本,需要使用setBackgroundDrawable方法来改变EditText的背景色。
在Android Lollipop版本中,如果想要改变颜色而不改变所有EditText的颜色,可以使用eText.setBackgroundColor方法。
示例代码如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KitKat) { // for Lollipop Version // do on textChangeListener code eText.setBackgroundDrawable(Color.RED); } else { // do on textChangeListener code eText.setBackgroundResource(Color.RED); }
希望这对你有所帮助,如果这段代码对你有用,请给我打分。谢谢。
问题出现的原因是因为背景Drawable被多个视图重用。为了确保Drawable不在多个视图之间共享,应该使用mutate方法。
解决方法如下:
Drawable background = mainMenuButton.getBackground(); background.mutate(); background.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.light_green), PorterDuff.Mode.MULTIPLY)); mainMenuButton.setBackground(background);
参考链接:[Android 5.0 Lollipop: setColorFilter "leaks" onto other buttons](https://stackoverflow.com/questions/27015811)