Android--Button自定义水波纹颜色方法

我们在使用Button时,默认点击会带有一个水波纹扩散的效果,如果我们想要使用自己的颜色,那怎么办呢,今天就来介绍二种实现自定义颜色水波纹的方法
方法一:使用drawable

在drawable-v21中新建selector_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimaryDark">
    <item android:drawable="@color/colorPrimary" />
</ripple>
使用该方法时,在安卓5.0以下系统中会崩溃,因为5.0以下不支持水波纹效果,所以我们需要在drawable中创建一个同名的xml,来兼容5.0以下

在drawable中新建selector_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimaryDark" android:state_pressed="true"/>
    <item android:drawable="@color/colorPrimary" />
</selector>
然后再xml中给button设置background
       <Button
            android:id="@+id/btn_next1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/selector_ripple"
            android:text="next" />
方法二:使用Theme

在styles中,自定义style

    <style name="MyButton" parent="Theme.AppCompat.Light">
        <item name="colorButtonNormal">@color/colorPrimary</item>
        <item name="colorControlHighlight">@color/colorPrimaryDark</item>
    </style>
然后再xml中给button设置theme
        <Button
            android:id="@+id/btn_next1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/MyButton"
            android:text="next" />
这种方法会自动兼容5.0以下,使用也更便洁
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容