0
<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

如何使用颜色而不是可绘制对象

我试过这个:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:color="@color/bg_blue"/>
    <item android:state_checked="false" android:color="@color/bg_light_grey"/>

</selector>

在名为bg_toggle.xml的颜色文件夹中定义了上述选择器

android:background="@color/bg_toggle"

这给出了一个例外:

android.view.InflateException: Binary XML file line #50: Error inflating class android.widget.ToggleButton

org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: tag requires a 'drawable' attribute or child tag defined a drawable

谢谢你

4

2 回答 2

5

尝试这个

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@color/bg_blue"/>
    <item android:state_checked="false" android:drawable="@color/bg_light_grey"/>

 </selector>

编辑

来自安卓文档

注意:颜色资源也可以用作 XML 中的可绘制对象。例如,在创建状态列表可绘制对象时,您可以为 android:drawable 属性 (android:drawable="@color/green") 引用颜色资源。

于 2012-12-20T13:49:36.583 回答
-2

而不是像这样尝试:

  ToggleButton btnToggle=(ToggleButton) findViewById(R.id.<Your ToggleButtonId>);
    btnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                buttonView.setBackgroundColor(Color.RED);
            else buttonView.setBackgroundColor(Color.GREEN);
        }
    });
于 2012-12-20T13:53:16.820 回答