やりたいこと
Androidで画像にリップル表現を実装する
考え方
リップル表現を適用したいImageViewをFragmentLayoutで囲む
FragmentLayoutにforeground属性を指定し、タップしたときにFragmentLayoutをタップできるようにする
foreground属性でリップル表現を適用する範囲と色を指定する
foreground属性は別途作成したxmlを参照させる
foreground属性を指定することによって、FrameLayoutが一番上のLayerになるので、タップイベントはFragmentLayoutが拾うことになる
実装
アプリのメインとなる画面のXML
activity_main.xml
<FrameLayout
android:id="@+id/image_view"
android:layout_width="150dp" // ポイント1:FragmentLayoutとImageViewのサイズは同じにする
android:layout_height="50dp"
android:padding="0dp" // ポイント2:リップル領域とImageViewがぴったり重なるようにpaddingは0dpとする
android:foreground="@drawable/btn_ripple"> // ポイント5:foregroundは「リップル領域」と「リップル時の色」を定義している別のxmlファイルのファイル名を参照させる
<ImageView
android:id="@+id/image_view2"
android:scaleType="fitXY" // ポイント3:FragmentLayoutとImageViewのサイズが同じになるように縦横比は可変とする
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_margin="0dp" // ポイント4:リップル領域とImageViewがぴったり重なるようにmarginは0dpとする
android:src="@drawable/long_circle" />
</FrameLayout>
btn_ripple.xml
// ポイント1:ファイル名は上記foreground属性で指定したものにする
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorRipple2"> // ポイント2:リップル時の色を指定する
<item
android:id="@android:id/mask" // ポイント3:ここは常に「mask」とする。たとえ他に「id/mask」を指定している箇所があったとしても。
android:drawable="@drawable/long_circle" /> // ポイント4:リップル領域を指定する。(リップルさせたいImageView自体を参照するだけでOK
</ripple>