【问题标题】:How to change color of the toggle button? [duplicate]如何更改切换按钮的颜色? [复制]
【发布时间】:2012-08-12 07:31:36
【问题描述】:

可能重复:
Change “on” color of a Switch

ToggleButton 将状态从 Green(true) 更改为 Red(false) 时,我需要更改颜色。如何更改ToggleButton 颜色?

【问题讨论】:

标签: android


【解决方案1】:

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

【讨论】:

  • 这不会产生很好的结果,因为它覆盖了标准按钮矩形形状。
  • 这会将整个按钮更改为绿色/红色。不是高亮颜色。
  • 此解决方案不适用于最新主题。
【解决方案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);
            }
        });

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2011-12-01
    • 2019-09-07
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多