Android 如何更改切换按钮的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11978880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:21:13  来源:igfitidea点击:

How to change color of the toggle button?

android

提问by David Dyon

Possible Duplicate:
Change “on” color of a Switch

可能的重复:
更改开关的“开启”颜色

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

ToggleButton当状态从绿色(真)变为红色(假)时,我需要改变颜色。我怎样才能改变ToggleButton颜色?

回答by SteveR

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

在 res/values 文件夹中创建一个名为 colors.xml 的 xml:

<?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:

在 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>

and in xml section define your toggle button:

并在 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"/>

回答by Art

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);
            }
        });