【Android】ボタンを押した時に波紋状のエフェクトを出す(Ripple Effect)
ボタンの背景色を変更するためにbackgroudで色指定をするとRipple Effectが表示されなくなる。
backgroudを変更するとRipple Effectの設定が上書きされて無くなってしまうため、自分で設定しないといけない。
Ripple Effectとは
ボタンを押したときに出る波紋状のエフェクトのこと。
Andoroid5.0ではRippleDrawableが導入され、実装が楽になった。
実装方法
ここではAndoroid5.0以降を対象に、RippleDrawableを利用して実装する。
やり方としては単純で、RippleDrawableを記述したXML(button_ripple.xml)を作成しておき、ボタンのbackground(activity_main.xml)からそれを呼び出すだけ。
(XMLじゃなくてJavaからでも実装できるが、ここではXMLからで実装する)
/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="20dp" android:background="@drawable/button_ripple" android:text="リップル!" /> </RelativeLayout>
/drawable/button_ripple.xml
<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/button_highlight_color"> <item android:drawable="@color/button_color" /> </ripple>
/values/colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="button_color">#ffffaab3</color> <color name="button_highlight_color">#ff4081</color> </resources>