将涟漪效果添加到已经自定义的按钮

5

我想为自定义按钮添加涟漪效果。但是我只找到了通过添加背景来实现这一点,我已经通过这种方式实现了按钮的圆角。现在我想要添加涟漪效果。以下是我的按钮标签:

<Button
    android:text="PLAY"
    android:id="@+id/button"
    android:textSize="20dp"
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:background="@drawable/roundedbutton"
    android:onClick="gotomainpage"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="200dp" />
3个回答

6

在你的按钮中使用这段代码

android:foreground="?attr/selectableItemBackground"

我在使用时遇到了这个错误。在'android'包中找不到属性'forground'的资源标识符。 - Usman Noor

5

简单易懂

1. 创建一个包含背景形状的涟漪可绘制对象

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?colorControlHighlight">         //defaul ripple color

    <item>
        <shape                                //the background shape when it's not being click
            android:shape="rectangle">

            <solid
                android:color="@color/colorPrimary" />

            <corners
                android:radius="32dp" />

        </shape>

    </item>

</ripple>

2. 将可绘制对象应用到按钮并去除阴影

<Button
    style="?borderlessButtonStyle"              //remove the default shadow
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_weight="1"
    android:background="@drawable/background_button"        //here
    android:text="Sign up"
    android:textAllCaps="false"
    android:textColor="@android:color/white" />

enter image description here


4
尝试添加android:foreground="@drawable/ripple"drawable/ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple_white">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

如果视图的边角有圆角,请在形状内应用此XML(否则涟漪会一直延伸到角落);
<corners android:radius="10dp"/>

如果您希望出现圆形涟漪,可以使用以下内容: drawable/ripple_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple_white">
    <item android:id="@android:id/mask">
        <shape android:shape="oval">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

这种方法需要最低API级别为21或更高,并且android:foreground在低于23的API级别上没有影响。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接