如何在 运行 时间更改可绘制资源?

How to change drawable resource at run time?

我想在运行时更改可绘制资源文件。

.java 文件代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button);
    edt1 = (EditText)findViewById(R.id.name);
    edt2 = (EditText)findViewById(R.id.password);
    str_name = edt1.getText().toString() ;
    str_password = edt2.getText().toString();

    if (str_name == 0 && str_password == 0) {
        btn.setBackgroundResource(R.drawable.image);
    }
    else {
        btn.setBackgroundResource(R.drawable.on_button_click);
    }

问题是它应用了 if 条件,但是当我在 EditText 中输入一些文本时,资源文件没有改变。

EditText(s) 在 TextInputLayout.

之下
  • TextUtils.equals判断str_name是否等于0.

  • TextUtils.equals判断str_password是否等于0.

试试这个。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button);
    edt1 = (EditText) findViewById(R.id.name);
    edt2 = (EditText) findViewById(R.id.password);
    str_name = edt1.getText().toString();
    str_password = edt2.getText().toString();

    // edited here
    if (TextUtils.equals(str_name, "0") && TextUtils.equals(str_password, "0")) {
        btn.setBackgroundResource(R.drawable.image);
    } else {
        btn.setBackgroundResource(R.drawable.on_button_click);
    }
}

另一种解决方法。

if (Double.parseDouble(str_name) == 0 && Double.parseDouble(str_password) == 0) {
    btn.setBackgroundResource(R.drawable.image);
} else {
    btn.setBackgroundResource(R.drawable.on_button_click);
}

用下面的代码替换你的条件语句

if (str_name.equalsIgnoreCase("0") && str_password.equalsIgnoreCase("0") {

    btn.setBackgroundResource(R.drawable.image);

}

您不能使用 == 来比较 2 个字符串。希望对你有帮助。