【Android】imageボタンが押された時の波紋の色を変更する

Android

imageボタンが押された時の波紋の色を変更するには、カスタムのリプル(波紋)エフェクトを定義して、ImageButtonに適用する方法があります

カスタムリプルエフェクトを定義する

res/drawableディレクトリにカスタムリプルエフェクトのXMLファイル(例えば、custom_ripple.xml)を作成します。

xml

<!-- res/drawable/custom_ripple.xml -->
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
        </shape>
    </item>
</ripple>

カスタムリプルエフェクトをImageButtonに適用する

次に、ImageButtonの背景としてカスタムリプルエフェクトを設定します。

xml

<!-- res/layout/activity_main.xml -->
<RelativeLayout 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"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_ripple"
        android:src="@drawable/ic_launcher_foreground"
        android:contentDescription="@string/app_name"/>
</RelativeLayout>

カスタムリプルカラーを定義する(オプション)

色をカスタマイズしたい場合は、アプリのテーマで使うカスタム属性を定義することができます。x

xml

<!-- res/values/attrs.xml -->
<resources>
    <attr name="customRippleColor" format="color"/>
</resources>

<!-- res/values/colors.xml -->
<resources>
    <color name="ripple_color">#FF0000</color> <!-- 例として赤色を設定 -->
</resources>

<!-- res/values/styles.xml -->
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlHighlight">@color/ripple_color</item>
    </style>
</resources>

これで、カスタムリプルエフェクトが適用され、波紋の色が変更されます

コメント