android原生button的点击效果,从点击处向控件四周做水波纹扩散。
最低版本为21,也就是5.0。
不但Button可以实现该效果,其他控件同样可以。
不同的系统版本的效果可能略微有差异。
关闭硬件加速该效果依然生效。
适合对控件有背景颜色的需求,若为白色背景,直接android:background="?android:attr/selectableItemBackground" 同样可实现点击水波纹效果
不受版本约束(推荐)
android:background="?selectableItemBackground"
android:background="?selectableItemBackgroundBorderless"
Android5.0以上
<!--波纹有边界-->
android:background="?android:attr/selectableItemBackground"
<!--波纹超出边界,只能在5.0以上使用-->
android:background="?android:attr/selectableItemBackgroundBorderless"
自定义实现(同样受版本约束)
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
style="@style/buttonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_10"
android:padding="@dimen/dp_6"
android:textColor="@color/white"
android:text="自定义Button"
android:textSize="@dimen/dp_20" />
<TextView
style="@style/buttonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_10"
android:padding="@dimen/dp_6"
android:textColor="@color/white"
android:text="自定义TextView"
android:textSize="@dimen/dp_20" />
<LinearLayout
style="@style/buttonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_10">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义LinearLayout"
android:textColor="@color/white"
android:textSize="@dimen/dp_20"
/>
</LinearLayout>
</LinearLayout>
style文件
<style name="buttonStyle" parent="Widget.AppCompat.Button" >
<item name="android:background">@drawable/button_backgroup</item>
</style>
drawable文件
<?xml version="1.0" encoding="utf-8"?>
<!--ripple 实现水波纹的关键,只支持21系统及以上-->
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@android:color/white"><!--手指点击控件的提示颜色,白色最好,透明会没效果,其他颜色会与背景色重叠,可能达不到想要的效果-->
<item>
<inset
android:insetLeft="4dp"
android:insetTop="1dp"
android:insetRight="4dp"
android:insetBottom="1dp"><!--在button中设置文字到边框的距离,数值越大,距离越小,若控件有padding设置,则inset此层可去掉-->
<!--rectangle ring line oval-->
<shape android:shape="rectangle"><!--控件的背景-->
<solid android:color="@color/s_dd0f27"/><!--控件的颜色-->
<corners android:radius="@dimen/dp_4"/><!--控件的圆角-->
</shape>
</inset>
</item>
</ripple>
在布局文件中用style="@style/buttonStyle"调用,控件显示英文字母会大写;5.0以后版本通过android:textAllCaps="false"解决,5.0之前没有问题
若用android:background="@drawable/button_backgroup"调用,只在Button中生效,其他控件不生效。