java 如何更改editText的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5973000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change background color of editText?
提问by artist
I need to change background color of EditText
if it is empty.
Below is my code but doesn't seem to be working.
EditText
如果它为空,我需要更改背景颜色。下面是我的代码,但似乎不起作用。
public void onClick(View v) {
// TODO Auto-generated method stub
Change();
}
public void Change() {
if(("").equals(name)) {
name.setBackgroundColor(Color.RED);
return;
}
}
回答by nicholas.hauschild
Assuming 'name' is the EditText in question, your if statement should read something like this:
假设 'name' 是有问题的 EditText,你的 if 语句应该是这样的:
if(("").equals(name.getText().toString()))
Performing an Object.equals(Object) between a String and an EditText (at least currently!) will not return true.
在 String 和 EditText(至少目前!)之间执行 Object.equals(Object) 不会返回 true。
回答by Shawn Lauzon
The easiest way is to check the length:
最简单的方法是检查长度:
if (name.length() == 0) {
name.setBackgroundColor(Color.RED);
}