2016-03-25 65 views
4

我只是希望通過文本的值更改按鈕的背景顏色。例如,當我將文本更改爲:Android如何通過文本更改按鈕顏色

button.setText("YES"); 

我想按鈕的背景顏色設置爲綠色。 當我將文本更改爲:

button.setText("NO"); 

我想按鈕的背景顏色設置爲紅色

當我改變它在Java代碼:

boolean textValueYES = true; 
button.setBackgroundColor(textValueYES ? Color.GREEN : Color.RED); 

按鈕失去其drawable.xml設置。 有沒有辦法將這種檢查添加到可繪製的XML? 或者通過文本值設置背景顏色而不丟失可繪製設置?

+0

要設置按鈕背景繪製使用'button.setBackgroundResource(textValueYES? R.drawable.greendrawable:R.drawable.reddrawable);' – AKSiddique

+0

創建帶有紅色背景色和綠色背景色的可繪製文件,如:red_drawable.xml,green_drawable.xml,並使用button.setBackgroundResource(R.drawable.red_drawable); –

回答

4

您可以爲紅色和綠色背景顏色創建兩個可繪製的xml,並以編程方式設置該xml。

button.setBackgroundResource(textValueYES ? R.drawable.green : R.drawable.red); 
3

你要做這樣的只寫下面的setText()的

button.setText("YES"); 
setBackgroundResource(R.color.green); 

button.setText("NO"); 
setBackgroundResource(R.color.red); 
1

我喜歡這在我的java文件

final Button btn_showtouch = (Button)findViewById(R.id.button); 
    btn_showtouch.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if((btn_showtouch.getText()).equals("YES")) { 
       btn_showtouch.setBackgroundColor(Color.GREEN); 
       btn_showtouch.setText("NO"); 
      }else if(btn_showtouch.getText().equals("NO")) { 
       btn_showtouch.setBackgroundColor(Color.CYAN); 
       btn_showtouch.setText("YES"); 
      } 

     } 
    }); 
} 

像這樣

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="YES" 
    android:id="@+id/button" 
    android:layout_below="@+id/textView" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginTop="62dp" /> 

和XML文件的工作對我來說,我希望這會幫助你