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

2020-02-26  本文已影响0人  aruba
我们在使用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以下,使用也更便洁
上一篇 下一篇

猜你喜欢

热点阅读