LoginSignup
5
5

More than 3 years have passed since last update.

【Android】リップルエフェクトとイベント遅延を併用したタップ時の演出

Posted at

概要

Androidアプリで、リストの要素やボタンなどをタップした時に、押したことが見て分かるようにしたいです。
Androidにはリップルエフェクトという波紋のようなエフェクトがあるので、それを設定することにします。
以下では、CardViewButtonについて説明します。

要素にリップルエフェクトを設定する

CardView

CardViewにリップルエフェクトを付ける場合、?android:attr/selectableItemBackgroundを設定するのが簡単です。

card.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="200dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:foreground="?android:attr/selectableItemBackground">
        <View
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:background="#EEEEEE" />
    </LinearLayout>
</com.google.android.material.card.MaterialCardView>

card-ripple-fore-loop.gif

backgroundに設定した場合は、以下のようにリップルがViewの下に隠れます。
card-ripple-back-loop.gif

Button

Buttonには標準でリップルエフェクトが付いていますが、backgroundを設定した場合は、リップルが付いていないもので上書きされてしまいます。
<ripple>を使うことで、リップル付きのbackgroundを設定できます。
以下では、リップル付きの角丸背景を作成しています(背景を角丸にした場合、foregroundでリップルを付けるとリップルが角からはみ出してしまいます)。

res/drawable/button_background.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
    <item>
        <shape>
            <solid android:color="#AABEFF"/>
            <corners android:radius="28dp"/>
        </shape>
    </item>
</ripple>

リップルエフェクトを付けたい要素のbackgroundに、先ほどのdrawableを指定します。

fragment.xml
<LinearLayout ...(略)>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/button_background" />
</LinearLayout>

イベントを遅延させる

例えばカードやボタンを押すと画面遷移をする時、OSのバージョンやデバイスによっては、リップルエフェクトの発生と同時に画面が遷移してリップルが見えない場合があります。
タップイベントの実行を遅らせて、リップルが見えるようにします。
処理の遅延にはHandler()を使っています。

Fragment.kt
item.setOnClickListener {
    Handler().postDelayed(object : Runnable {
        override fun run() {
            // タップした時の処理
        }
    }, 100) // 遅延させたい時間をミリ秒で指定
}

まとめ

  • カードやボタンを押した時にリップルエフェクトが発生するようにしました。
  • リップルが見えるようにタップした時の処理の実行を遅らせました。

参考

https://qiita.com/nissiy/items/bf2742ffb990e3c8f875
https://qiita.com/hkusu/items/32b96eef9bbaafb2dea6

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5