android カスタマイズCompoundButtonにリップル効果を追加
カスタムのCompoundButtonにリップル効果を追加するには、次の手順を実行します。
- 波及効果のスタイルと色を定義するために、新しいdrawableファイル ripple_effect.xmlを作成します:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/ripple_effect_color">
<item android:id="@android:id/mask">
<shape android:shape="oval">
<solid android:color="@android:color/white" />
</shape>
</item>
</ripple>
上記のコードでは、ripple_effect_colorは波紋効果の色で、必要に応じて調整できます。
- カスタムCompoundButtonのレイアウトファイルにて、リップル効果の描画ファイルをCompoundButtonの背景に指定する
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/custom_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ripple_effect"
... />
<!-- 其他布局代码 -->
</RelativeLayout>
上記のコードではチェクボックスの背景にリップル効果のドロワーブルファイルである ripple_effect を設定しています。
- カスタム CompoundButton の Java コードで、CompoundButton にクリックイベントリスナーを設定し、クリックイベントでリップル効果を処理します。
CheckBox customCheckbox = findViewById(R.id.custom_checkbox);
customCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 处理选中状态下的涟漪效果
buttonView.setBackgroundResource(R.drawable.ripple_effect);
} else {
// 处理未选中状态下的涟漪效果
buttonView.setBackgroundResource(0);
}
}
});
チェックされたCompoundButtonの選択状態が変更された場合に、isCheckedの値に応じてリップル効果を処理しています。チェックされている場合、リップル効果のドローアブルファイルをセットし、チェックされていない場合はnullまたは0セットします。
これにより、カスタムCompoundButtonにリップル効果を追加できるようになりました。