【问题标题】:Android: toggle text color of ToggleButtonAndroid:切换ToggleButton的文本颜色
【发布时间】:2012-12-13 11:08:48
【问题描述】:

为了创建自定义切换按钮,我在/res/values/styles.xml 中定义了一个新样式:

<style name="myToggleButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#000000</item>
    <item name="android:background">@drawable/my_toggle_button</item>
</style>

然后我使用选择器指定按钮状态在/res/drawable/my_toggle_button.xml 中的外观:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape>
            [...]
        </shape>
    </item>
    <item android:state_checked="false"
        <shape>
            [...]
        </shape>
    </item>
</selector>

如何修改此设置以在状态更改时切换按钮的文本颜色?

【问题讨论】:

  • 在形状范围内,给你想要的颜色参数,并在 style.xml 中删除背景。
  • 我认为这个链接对你的问题很有用:stackoverflow.com/questions/7096599/…
  • 基于 Eclipse 中的自动完成实验,该链接没有给出有效的语法。指定颜色的唯一可能方法是在&lt;item&gt; 范围内的&lt;color android:color=""/&gt;。不过,它不会改变文本颜色。

标签: android android-xml togglebutton


【解决方案1】:

为您想要的文本颜色创建一个类似的状态列表,并将其放在res/color,例如

res/color/toggle_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#070" />
    <!-- Default State -->
    <item android:color="#A00" />
</selector>

然后将此资源设置为按钮的文字颜色:

<item name="android:textColor">@color/toggle_color</item>

P.S.,最好让选择器中的最后一项不附加任何状态标志(即默认状态),而不是使用与上述状态相反的状态来定义它。

【讨论】:

  • 非常有用的答案 - 但我发现它没有运行只是因为文件名中不允许使用大写字符(至少 API 版本 18) - 进行了编辑:)
猜你喜欢
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多