【问题标题】:How to use a color instead of drawable for toggle button selector如何为切换按钮选择器使用颜色而不是可绘制
【发布时间】:2012-12-08 01:14:48
【问题描述】:
<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>

如何使用 color 而不是 drawable

我试过了:

<?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:二进制 XML 文件第 50 行:错误膨胀类 android.widget.ToggleButton

org.xmlpull.v1.XmlPullParserException:二进制 XML 文件第 4 行:标签需要“drawable”属性或定义可绘制对象的子标签

谢谢

【问题讨论】:

    标签: android xml android-layout selector togglebutton


    【解决方案1】:

    试试这个

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

    编辑

    来自安卓Doc

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

    【讨论】:

    • 我可以在 drawable 属性中使用 color 吗?像 android:drawable="@color/bg_blue"
    【解决方案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);
            }
        });
    

    【讨论】:

    • 使用 xml 选择器处理 ui 状态通常被认为是更好的做法。
    猜你喜欢
    • 2015-01-03
    • 2020-06-06
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多