如何在 android 中设置具有波纹效果的按钮背景可绘制图像

How to set button background drawable image with ripple effect in android

我的Xml代码:

<Button
    android:id="@+id/link_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/google_btn" />

我正在应用默认波纹效果

<Button
    android:id="@+id/link_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground" />

但我需要按钮背景 "@drawable/google_btn"
"?android:attr/selectableItemBackground"。这意味着我需要自定义背景的连锁反应。

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

    <item
        android:id="@android:id/mask"
        android:drawable="@drawable/btn_rectangle"/>
    <item android:drawable="@drawable/btn_rect_states"/>

</ripple>

在 drawables 中尝试上面的代码,根据需要提供您自己的自定义 drawable 背景。

在您的 drawable-v21 文件夹中,您可以自己编写连锁反应代码。制作一个可绘制的 xml 文件并通过 ripple 设置起始标记。像这样:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/colorAccentDark">
    <item>
        <selector xmlns:android="http://schemas.android.com/apk/res/android" >
            <item
                android:drawable="@color/button_accent_dark"
                android:state_checked="false"/>
            <item
                android:drawable="@color/button_accent"
                android:state_checked="true" />
            <item
                android:drawable="@color/button_accent_dark" />

        </selector>
    </item>
</ripple>

当按钮有来自 drawable 的背景时,我们可以为前景参数添加波纹效果。检查下面的代码是否适用于我的具有不同背景的按钮

<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center"
android:layout_centerHorizontal="true"                                                             
android:background="@drawable/shape_login_button"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:text="@string/action_button_login"
 />

为波纹效果添加以下参数

android:foreground="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:focusable="true"

另一种选择是创建可绘制的图层列表并将其设置为背景。例如:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_background"/>
    <item android:drawable="?attr/selectableItemBackground"/>
</layer-list>