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" /&gt;

这是由于在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" /&gt;

将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_transparentcolor文件夹推荐自建,也可以放在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" />

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

原文地址:https://blog.csdn.net/Me_Rui/article/details/129263617

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_23424.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注