android - 使用按钮背景颜色为我的按钮添加波纹效果?

我创建了一个按钮,我想为该按钮添加波纹效果!

我创建了一个按钮 bg XML 文件:(bg_btn.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient android:startColor="#FFFFFF" android:endColor="#00FF00" android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>

这是我的涟漪效果文件:(ripple_bg.xml)

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#f816a463"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
        </shape>
    </item>
</ripple>

这是我想要添加涟漪效果的按钮:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="173dp"
android:textColor="#fff"
android:background="@drawable/ripple_bg"
android:clickable="true" />

但是添加波纹效果后按钮背景是透明的,而且按钮只有在点击时才会显示, 像这样:

点击前

点击

但我需要按钮背景颜色和波纹效果, 我在 Stack Overflow 的不同博客中找到了其中一些代码,但仍然无法正常工作!

最佳答案

对于那些想要将渐变背景、圆角半径和波纹效果加在一起的人来说,这是另一个可绘制的 xml:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimaryDark">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <gradient
                android:angle="90"
                android:endColor="@color/colorPrimaryLight"
                android:startColor="@color/colorPrimary"
                android:type="linear" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>
</ripple>

将此添加到按钮的背景中。

<Button
    ...
    android:background="@drawable/button_background" />

PS:此答案适用于 android api 21 及更高版本。

https://stackoverflow.com/questions/40008609/

相关文章:

android - 如何在 Activity 启动时在 ScrollView 中滚动到底部

android - 如何检查 Activity 是在前台还是在可见背景中?

android - 如何将值从一个 Activity 传递到上一个 Activity

android - SearchView 的 OnCloseListener 不起作用

android - 如何检测Android中布局的方向变化?

android - 获取 backstack 中的最新 fragment

android - 带有完成操作按钮的多行 EditText

android - 同步 ScrollView 滚动位置 - android

android - 无法修改 ListView 中的 ArrayAdapter : Unsuppor

android - 带有阴影的自定义 ImageView