首页 > 解决方案 > 更改切换按钮的颜色

问题描述

在此处输入图像描述有没有办法以编程方式更改切换按钮的切换颜色,而不是背景颜色。

我在文档中没有看到对它的引用。

https://developer.android.com/reference/android/widget/ToggleButton.html#setBackgroundDrawable(android.graphics.drawable.Drawable)

标签: androidandroid-button

解决方案


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

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

最后但并非最不重要的 :)

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_selected" android:state_checked="true" android:state_pressed="true"/>
<item android:drawable="@drawable/bg_selected" android:state_checked="true" android:state_focused="false"/>
<item android:drawable="@drawable/bg_normal" android:state_checked="false" android:state_pressed="true"/>
<item android:drawable="@drawable/bg_normal" android:state_checked="false" android:state_focused="false"/>


推荐阅读