根据带有兼容库的状态更改 FAB 的图标颜色

Change icon color of FAB based on state w/ compat libs

我正在尝试根据按钮状态更改 FAB 中图标的图标颜色:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/search_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:tint="@color/add_button_tint"
    android:src="@drawable/ic_add_black_24dp" />

add_button_tint.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:color="@color/white" />

    <item android:color="@color/black"/>
</selector>

这在 API > 23 中运行良好,但在 android 的旧版本中,它会抛出异常。

这是我感到困惑的地方:

android:tint 属性 存在于支持 FAB 中,如果它只是一种颜色,即使在 android 的旧版本中也是如此。 IE 这适用于我测试的所有版本:

android:tint="@color/black

但是当我使用选择器时却没有。我究竟做错了什么?是否可以在旧版本 android 中根据 FAB 的状态更改图标颜色?

ColorStateList in android:tint was not supported prior to API 21.

参见:https://code.google.com/p/android/issues/detail?id=204671


您可以使用 AppCompat 的 AppCompatResources 和 support-v4 DrawableCompat 来支持 pre-lollipop。首先,从布局中删除 android:tint="@color/add_button_tint"。然后以编程方式设置 ColorStateList

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.search_button);
ColorStateList csl = AppCompatResources.getColorStateList(this, R.color.add_button_tint);
Drawable drawable = DrawableCompat.wrap(fab.getDrawable());
DrawableCompat.setTintList(drawable, csl);
fab.setImageDrawable(drawable);