安卓:切换按钮的切换文本颜色按钮、文本、颜色

2023-09-06 13:33:23 作者:清酒寄风

要创建一个自定义切换按钮,我已经定义了一个新的风格 /res/values​​/styles.xml

To create a custom ToggleButton, I've defined a new style in /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

and I then use a selector to specify how the button's states look in /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>

我怎么能修改此设置来切换按钮的文字颜色时态变化?

How can I modify this setup to toggle the text color of the button when the state changes?

推荐答案

创建一个类似的状态列表的文本颜色,你想,并把它放在 RES /颜色 ,如:

Create a similar state list for the text colors you would like, and place it in res/color, e.g.

RES /彩色/ 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>

然后设置此资源作为按钮的文本颜色:

Then set this resource as the text color of the button:

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

PS,这是很好的做法,最后一个项目的选择没有连接(即默认状态)任何状态的标志,而不是上述国家的倒数定义它。

P.S., it's good practice to have the last item in a selector not have any state flags attached (i.e. a default state) rather than defining it with the inverse of the above states.