如何在按下时更改 android AppCompatButton 文本颜色

How to change android AppCompatButton's text color on pressed

我为自定义 AppCompatButton 创建了以下样式。

<style name="AppTheme.secondary_button" parent="Base.Widget.AppCompat.Button">
    <item name="colorButtonNormal">@color/secondary_button_color</item>
    <item name="colorControlActivated">@color/menu_blue</item>
    <item name="android:colorButtonNormal">@color/secondary_button_color</item>
    <item name="android:textColorPrimary">@color/gray</item>
    <item name="android:textColor">@color/gray</item>
</style>

按下按钮时更改文本颜色的属性是什么?

为此,您只需用选择器替换您指定的 textColor:

像这样:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white" />
    <item android:state_focused="true" android:color="@color/grey" /> <!-- (for accessibility) -->
    <item android:color="@color/black" />
</selector>

然后像这样赋值: android:textColor="@drawable/button_foreground_selector"

<android.support.v7.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    style="@style/CustomAppCompatButtonStyle"
    android:text="Hi, Neo"/>

未点击按钮:

点击按钮:

我使用的样式:

<style name="CustomAppCompatButtonStyle" parent="Base.Widget.AppCompat.Button">
    <item name="colorButtonNormal">@color/red</item>
    <item name="colorControlActivated">@color/blue</item>
    <item name="android:colorButtonNormal">@color/green</item>
    <item name="android:textColorPrimary">@color/gray</item>
    <item name="android:textColor">@drawable/button_foreground_selector</item>
</style>