如何修改Android中Material Switch组件的点击放射阴影颜色
解决方案
你遇到的绿色点击放射阴影是Material组件默认的涟漪(Ripple)效果,默认取App主题的colorSecondary属性值,所以单独修改轨道和滑块颜色不会同步修改这个效果的颜色,SwitchMaterial提供了专门的rippleColor属性来配置该颜色,两种修改方式如下:
方法1:直接在布局中添加属性修改
直接给你的SwitchMaterial控件新增app:rippleColor属性即可,修改后的布局代码如下:
<com.google.android.material.switchmaterial.SwitchMaterial android:id="@+id/switch_compat" android:layout_width="wrap_content" android:layout_height="wrap_content" app:trackTint="@color/purple_500" app:thumbTint="@color/purple_700" <!-- 新增涟漪颜色配置,可直接填色值或引用color资源 --> app:rippleColor="@color/purple_200" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
如果需要区分不同状态的涟漪颜色,可以在res/color目录下创建颜色状态列表文件,比如switch_ripple_color.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 开关选中状态的涟漪色 --> <item android:alpha="0.2" android:color="@color/purple_700" android:state_checked="true" /> <!-- 开关未选中状态的涟漪色 --> <item android:alpha="0.2" android:color="@color/purple_200" android:state_checked="false" /> </selector>
之后把app:rippleColor的值设置为@color/switch_ripple_color即可。
方法2:通过自定义样式全局配置
如果项目中所有SwitchMaterial都需要统一的涟漪颜色,可以在styles.xml中自定义样式:
<style name="CustomPurpleSwitch" parent="Widget.MaterialComponents.CompoundButton.Switch"> <item name="trackTint">@color/purple_500</item> <item name="thumbTint">@color/purple_700</item> <item name="rippleColor">@color/switch_ripple_color</item> </style>
之后在布局中给SwitchMaterial控件设置style即可:
<com.google.android.material.switchmaterial.SwitchMaterial android:id="@+id/switch_compat" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/CustomPurpleSwitch" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
内容的提问来源于stack exchange,提问作者user2424380
相关产品推荐
相关产品推荐

