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

标签 android material-design android-styles floating-action-button

我正在尝试根据按钮状态更改 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);

参见 How to use setImageTintList() on Android API < 21

关于android - 根据带有兼容库的状态更改 FAB 的图标颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033086/

相关文章:

android - 对话框中的自定义复选框样式

android - 如何修复应用程序启动时的白屏?

android - 使用预编译 header 时 GCC 失败且没有消息

自 Android Studio 4.1 起,Android Background Drawable 在按钮中不起作用

javascript - Material Design Lite 动态改变颜色

android - 删除自定义对话框上的黑色背景

android - 在 mp4Parser 的帮助下修剪视频

android - 间接引用(别名)到android中的自定义xml属性

Android Material 主题 alpha 颜色问题

android - 无法更改开关颜色