如何解决Jetpack Compose中FAB渐变背景上图标出现白色阴影的问题
解决Jetpack Compose渐变背景FAB图标泛白问题
问题原因
- 你遇到的图标泛白是
FloatingActionButton默认自带的elevation(高度阴影)效果导致的:你将FAB的背景色设为透明后,默认的阴影层会显示在自定义渐变背景和图标之间,就出现了泛白的视觉效果。 FloatingActionButton默认的elevation在不同交互状态(默认、按下、聚焦、悬浮)下都有非0值,哪怕静态状态下也会有默认阴影。
修复方案(基于现有代码修改)
直接给FloatingActionButton添加elevation参数,将所有状态的高度都设为0即可,修改后的FAB代码如下:
FloatingActionButton( onClick = { coroutineScope.safeLaunch { navController.navigate("AddTodoPage") { launchSingleTop = true } } }, shape = RoundedCornerShape(14.dp), backgroundColor = Color.Transparent, // 新增这段代码关闭所有状态的elevation elevation = FloatingActionButtonDefaults.elevation( defaultElevation = 0.dp, pressedElevation = 0.dp, focusedElevation = 0.dp, hoveredElevation = 0.dp ), modifier = Modifier .constrainAs(addFab) { bottom.linkTo(parent.bottom) end.linkTo(parent.end) } .offset(x = (-16).dp, y = (-24).dp) .background( brush = Brush.verticalGradient( colors = BluePinkGradient() ), shape = RoundedCornerShape(14.dp) ) ) { Icon( painter = painterResource(id = R.drawable.ic_add), contentDescription = "Add icon", tint = Color.White ) }
更优的渐变FAB实现方案
如果不需要使用FloatingActionButton自带的各类交互效果,你也可以直接用Box+点击事件实现,逻辑更简单,不会被默认属性干扰:
Box( modifier = Modifier .constrainAs(addFab) { bottom.linkTo(parent.bottom) end.linkTo(parent.end) } .offset(x = (-16).dp, y = (-24).dp) .size(56.dp) // FAB默认标准尺寸,可按需调整 .background( brush = Brush.verticalGradient(colors = BluePinkGradient()), shape = RoundedCornerShape(14.dp) ) .clickable { coroutineScope.safeLaunch { navController.navigate("AddTodoPage") { launchSingleTop = true } } }, contentAlignment = Alignment.Center ) { Icon( painter = painterResource(id = R.drawable.ic_add), contentDescription = "Add icon", tint = Color.White ) }
如果需要保留水波纹点击效果,给clickable modifier添加indication和interactionSource参数即可。
内容的提问来源于stack exchange,提问作者Vicki Mes
相关产品推荐
相关产品推荐

