Android:切换ToggleButton的文本颜色

时间:2012-12-28 05:51:44

标签: android android-xml togglebutton

要创建自定义ToggleButton,我在/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>

当状态发生变化时,如何修改此设置以切换按钮的文本颜色?

1 个答案:

答案 0 :(得分:69)

为您想要的文字颜色创建一个类似的状态列表,并将其放在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。,最好让选择器中的最后一项没有附加任何状态标志(即默认状态),而不是用上述状态的倒数来定义它。