2017-10-14 93 views
-3

我想在運行時更改可繪製資源文件。如何在運行時更改drawable資源?

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之下。

+3

您不能使用==比較字符串。使用.equals()方法 – UltimateDevil

+0

而且您甚至無法將對象與整數進行比較,就像您當前正在嘗試的那樣。 –

+0

你可以檢查我的答案。 – KeLiuyue

回答

0
  • 使用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); 
} 
0

與下面的代碼

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

    btn.setBackgroundResource(R.drawable.image); 

} 

不能使用==比較兩個字符串替換你的條件語句。希望能幫助你。

+0

但是當我在編輯文本中輸入文本時沒有更改按鈕值 –

+0

對EditText和EditText的addTextChangeListener方法使用此答案,並將abdul的waheed代碼放在afterTextChanged方法中。 –

+0

@ChiragJain謝謝你,我工作得很好,因爲我需要 –