-1

I want to change the drawable resource file at runtime.

.java file code

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);
    }

The thing is that it applies the if condition but when I enter some text in the EditText the resource file does not change.

EditText(s) are under TextInputLayout.

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Uzair Mughal
  • 309
  • 4
  • 15

2 Answers2

2
  • Use TextUtils.equals to judge whether str_name equals 0 or not .

  • Use TextUtils.equals to judge whether str_password equals 0 or not .

Try this .

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);
    }
}

Another way to solve it .

if (Double.parseDouble(str_name) == 0 && Double.parseDouble(str_password) == 0) {
    btn.setBackgroundResource(R.drawable.image);
} else {
    btn.setBackgroundResource(R.drawable.on_button_click);
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
0

Replace your conditional statement with below code

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

    btn.setBackgroundResource(R.drawable.image);

}

You cannot use == for comparing 2 strings. Hope that helps you.

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58