效果图:
本文介绍的是Android5.0中其中一个炫酷的效果,点击水波纹扩散效果(Ripple Effect).
以下介绍的实现方式都是调用Android5.0的新API,并非自定义实现,所以只支持在Android5.0及以上的设备.
而大家想兼容低系统版本的话,就需要新建v21(即Android5.0)的Resource Directory.
实现:
1、在drawable下新建一个圆角的背景图 button_bg_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<corners android:radius="5dp" />
</shape>
2、是API 21才有的新Tag,正是实现水波纹效果的 ,在drawable-v21文件夹下,新建 button.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorPrimary">
<item android:drawable="@drawable/button_bg_normal"/>
</ripple>
注:ripple属性下类似与FragmentLayout,item最下面的会覆盖最上面的
顺便说下非水波纹button点击效果: 新建button点击下,背景图:button_bg_press.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent" />
<corners android:radius="5dp" />
</shape>
新建button_select.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_bg_press" android:state_pressed="true" />
<item android:drawable="@drawable/button_bg_normal" android:state_pressed="false"/>
</selector>
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context="test.xl.com.myapplication.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:background="@drawable/button"
android:text="水波纹" />
</LinearLayout>