Android Button修改背景颜色及实现Button水波纹效果

Android Button修改背景颜色及实现Button水波纹效果,效果如下:

以下基于API33(Android13.0),向下兼容至API24(Android7.0)。

1.修改Button背景

我们可以发现在布局xml文件中直接修改background是没有作用的,会变成默认的主题色(themes.xml中的colorPrimary颜色,默认为紫色)

<Button
   android:id="@+id/dialog_button"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="105dp"
   android:background="@drawable/ripple_grey_e"
   android:text="确定"
   android:textColor="@color/grey_3"
   android:textSize="@dimen/main_text"
   tools:ignore="TouchTargetSizeCheck" />

这是由于在Android4.1之后的开发中创建的Button是Material类型的,默认使用主题色的,所以我们需要替换主题色或者使用非Material类型的Button,修改如下:

<android.widget.Button
   android:id="@+id/dialog_button"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="105dp"
   android:background="@drawable/ripple_grey_e"
   android:text="确定"
   android:textColor="@color/grey_3"
   android:textSize="@dimen/main_text"
   tools:ignore="TouchTargetSizeCheck" />

将Button修改为android.widget.Button标签即可。

2.实现按压水波纹效果

首先在drawable文件夹中创建ripple类型的xml文件,例如我创建的ripple_grey_e.xml文件:

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

其中的@color/grey_e为colors.xml文件中定义的颜色(这个颜色就是水波纹的颜色,此处为浅灰色#eeeeee,示例动图中为使效果明显替换为了深灰色#333333),@color/selector_btn_transparent为color文件夹(推荐自建,也可以放在drawable文件夹中),selector_btn_transparent.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--按压下时-->
    <item android:state_pressed="true" android:color="@color/grey_f7" />
    <item android:color="@color/transparent"/>
</selector>

 grey_f7为浅灰色(#f7f7f7),transparent为透明色(#00ffffff)。

使用如下:

<android.widget.Button
   android:id="@+id/dialog_button"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="105dp"
   android:background="@drawable/ripple_grey_e"
   android:text="确定"
   android:textColor="@color/grey_3"
   android:textSize="@dimen/main_text"
   tools:ignore="TouchTargetSizeCheck" />

 本示例采用颜色较浅,如果想使效果更加明显,可以将颜色换为更加明显的颜色。

猜你喜欢

转载自blog.csdn.net/Me_Rui/article/details/129263617