AppCompatButton backgroundTint API < 21

AppCompatButton backgroundTint API < 21

我想在按钮上使用波纹效果。 AppCompat v22.1 添加了 AppCompatButton 和 AppCompat 着色的新功能。

我的布局:

<android.support.v7.widget.AppCompatButton
        android:id="@+id/add_remove_button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:backgroundTint="@color/primary"
        android:textColor="@android:color/white"
        android:text="Remove" />

在我的 API 22 测试设备上,涟漪效应完美运行,但我正在为 API 11 编码,不幸的是 backgroundTint 需要 API >= 21。我如何设置旧 API 版本对按钮的连锁反应?

Ripple 在 Android <21 上无法作为内置功能使用。这是由于性能问题:具有新 API 的设备可以使用旧设备无法使用的 RenderThread。 另见:http://android-developers.blogspot.de/2014/10/appcompat-v21-material-design-for-pre.html

Why are there no ripples on pre-Lollipop? A lot of what allows RippleDrawable to run smoothly is Android 5.0’s new RenderThread. To optimize for performance on previous versions of Android, we've left RippleDrawable out for now.

只需使用app:backgroundTint代替android:backgroundTint,色调将在Lollipop以下生效。原因是AppCompatActivityAppCompatDelegateImplV7使用AppCompatViewInflater将Button或TextView自动更改为AppCompatButton或AppCompatTextView,然后app:backgroundTint生效。

要支持 API21 以下的涟漪功能,您可能需要在按钮的背景中添加可绘制对象:

<android.support.v7.widget.AppCompatButton
    android:id="@+id/add_remove_button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/button_ripple"
    android:backgroundTint="@color/primary"
    android:textColor="@android:color/white"
    android:text="Remove" />

然后你必须在 drawable 和 drawable-v21 目录中添加同名的 xml(如果你没有它们,你可以创建它们,它们将自动链接)。

/res/drawable-v21/button_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/white">
    <item>
        <shape>
            <solid android:color="@color/white" />
        </shape>
    </item>
</ripple>

/res/drawable/button_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="@color/white" />
        </shape>
    </item>
</selector>

我正在分享我的用例:它是 ImageView:

app:backgroundTint 没有生效,因为我在该 Imageview 中为背景图像使用了 android:src 标签。

当我为 Imageview 将其更改为 android:background 时,app:backgroundTint 完美运行。

应该使用的不同答案提到的第二个用例

androidx.appcompat.widget.AppCompatImageView

而不是 ImageView