可能重复:
更改开关的“开启”颜色
当状态从绿色(真)变为红色(假)时,我需要ToggleButton
改变颜色。我怎样才能改变ToggleButton
颜色?
在 res/values 文件夹中创建一个名为 colors.xml 的 xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff0000</color>
<color name="green">#00ff00</color>
</resources>
在 drawable 文件夹中,创建一个 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"/>
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);
}
});