【问题标题】:How to change ToggleButton color using android:color?如何使用 android:color 更改 ToggleButton 颜色?
【发布时间】:2018-11-19 09:38:43
【问题描述】:

我想根据状态更改 ToggleButton 颜色。我找到了解决方案,但它不起作用。

<?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/buttonA"/>
     <item android:state_checked="false" android:color="@color/buttonDisabled"/>
</selector>

我不能使用 android:color,这里只允许使用 android:drawable。 (得到这个例外)

Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #3: <item> tag requires a 'drawable' attribute or child tag defining a drawable

【问题讨论】:

  • 将您的选择器文件放入res&gt;color&gt;your_selector.xml

标签: android android-button android-togglebutton


【解决方案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"/> 

在这里了解更多信息是link

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 2019-04-29
    • 1970-01-01
    • 2019-07-30
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多