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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:46:32  来源:igfitidea点击:

How to change background color of editText?

javaandroid

提问by artist

I need to change background color of EditTextif 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);
}