2012-08-15 75 views
8

可能重复:
Change “on” color of a Switch如何更改切换按钮的颜色?

我需要有一个ToggleButton改变颜色,当它从绿色(真)状态,以红色(假)。如何更改ToggleButton颜色?

+0

这有人准备好了被问及在这里回答,由我:):http://stackoverflow.com/questions/11253512/change-on-color-of-a-switch/11253636#11253636 – you786 2012-08-15 23:57:48

+2

有没有答案:(( – 2012-08-16 00:00:47

回答

-2

只需使用setBackgroundColor;)

更新: 这里也是一个不错的选择。 Standard Android Button with a different color

p.s.为什么要给予downvote求助?

+12

-1因为setBackgroundColor会更改按钮的背景,而不是所要求的ToggleButton的开/关颜色。 – you786 2012-08-16 00:02:56

20

中创建一个名为RES XML colors.xml /值文件夹:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="red">#ff0000</color> 
    <color name="green">#00ff00</color> 
</resources> 

在绘制文件夹中创建一个XML文件my_btn_toggle.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_checked="false" android:drawable="@color/red" /> 
    <item android:state_checked="true" android:drawable="@color/green" /> 
</selector> 

和XML部分定义切换按钮:

<ToggleButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New ToggleButton" 
    android:id="@+id/toggleButton" 
    android:background="@drawable/my_btn_toggle"/> 
+2

这并没有给出很好的结果,因为它覆盖了标准按钮的矩形形状。 – 2015-10-04 16:30:23

+1

这将整个按钮更改为绿色/红色。不是高光颜色。 – 2016-01-13 21:54:38

+0

此解决方案不适用于最新的主题。 – 2016-03-11 11:56:00

2
ToggleButton Btn=new ToggleButton(this);// or get it from the layout by ToggleButton Btn=(ToggleButton) findViewById(R.id.IDofButton); 
     Btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       // TODO Auto-generated method stub 
       if(isChecked) 
        buttonView.setBackgroundColor(Color.GREEN); 
       else buttonView.setBackgroundColor(Color.RED); 
      } 
     });