11

Possible Duplicate:
Change “on” color of a Switch

I need to have a ToggleButton change color when it changes state from Green(true) to Red(false). How can I change ToggleButton color?

Community
  • 1
  • 1
David Dyon
  • 173
  • 1
  • 2
  • 6
  • This has already been asked and answered here, by me :) : http://stackoverflow.com/questions/11253512/change-on-color-of-a-switch/11253636#11253636 – you786 Aug 15 '12 at 23:57

2 Answers2

30

Create a xml named colors.xml in res/values folder:

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

In drawable folder, create a xml file 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>

and in xml section define your toggle button:

<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"/>
Sadık
  • 4,249
  • 7
  • 53
  • 89
SteveR
  • 2,496
  • 1
  • 24
  • 23
7
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);
            }
        });
Art
  • 141
  • 1
  • 10