Compose新版本禁用Button的Ripple效果遇问题:新代码无效旧方法废弃
问题描述
我想禁用Button的涟漪(Ripple)效果,查阅官方文档《Migrate to Indication and Ripple APIs》后,得知需将旧代码:
private object DisabledRippleTheme : RippleTheme { @Composable override fun defaultColor(): Color = Color.Transparent @Composable override fun rippleAlpha(): RippleAlpha = RippleAlpha(0f, 0f, 0f, 0f) } // ... CompositionLocalProvider(LocalRippleTheme provides DisabledRippleTheme) { Button { // ... } }
替换为新代码:
CompositionLocalProvider(LocalRippleConfiguration provides null) { Button { // ... } }
但新代码在我的环境中无效,请问该代码存在版本限制吗?另外我尝试重写RippleTheme时,还收到错误提示:"Using 'RippleTheme' is an error. RippleTheme and LocalRippleTheme have been deprecated"(中文翻译:“使用‘RippleTheme’是错误的。RippleTheme和LocalRippleTheme已被废弃”)
解决方案
1. LocalRippleConfiguration的版本限制
LocalRippleConfiguration是Jetpack Compose Material3 1.2.0及以上版本才引入的API,仅适用于Material3组件:
- 若项目使用Material2,或Material3版本低于1.2.0,该API会无效;
- 即使在符合版本要求的环境中,直接给Button设置
indication = null的方式比通过CompositionLocalProvider更直接可靠:
Button( onClick = { /* 点击逻辑 */ }, indication = null, interactionSource = remember { MutableInteractionSource() } ) { Text("无涟漪按钮") }
注意:必须搭配
interactionSource参数,否则可能导致按钮的交互状态(如按压高亮)异常。
2. 低版本或Material2的替代方案
由于RippleTheme和LocalRippleTheme已被废弃,在Material2或低版本Material3中,可使用NoIndication禁用涟漪:
方式一:全局设置
CompositionLocalProvider(LocalIndication provides NoIndication) { Button(onClick = { /* 点击逻辑 */ }) { Text("无涟漪按钮") } }
方式二:直接给Button设置参数
Button( onClick = { /* 点击逻辑 */ }, indication = NoIndication, interactionSource = remember { MutableInteractionSource() } ) { Text("无涟漪按钮") }
错误提示的原因
RippleTheme是Jetpack Compose早期(主要是Material2)的API,随着Indication体系的统一,该API已被废弃,官方推荐使用Indication相关接口(如NoIndication、LocalIndication)控制涟漪效果。
内容的提问来源于stack exchange,提问作者Fatima Jamal
相关产品推荐
相关产品推荐

