Jetpack Compose中OutlinedButton实现透明背景且保留主题默认色
问题原因
你仅自定义了OutlinedButton的背景色为透明,未指定内容色,Compose按钮组件会自动根据背景对比度匹配默认内容色,透明背景下默认会取黑色的OnSurface主题色,导致原有的蓝色主色丢失。
解决方法
在colors参数中同时指定contentColor为主题默认的主色即可,按钮内部的文字和图标会自动继承该内容色,无需单独给子组件设置颜色,修改后的代码如下:
OutlinedButton( colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = MaterialTheme.colors.primary ), border = BorderStroke(0.dp, Color.Transparent), modifier = modifier, onClick = onClick ) { icon?.invoke() Text( text = value, fontSize = 12.sp ) }
优化方案(可选)
如果你不需要使用OutlinedButton的边框相关特性,直接使用TextButton组件更简洁,该组件默认就是透明背景无边框,自带主题主色的内容色,代码如下:
TextButton( modifier = modifier, onClick = onClick ) { icon?.invoke() Text( text = value, fontSize = 12.sp ) }
内容的提问来源于stack exchange,提问作者edi233
相关产品推荐
相关产品推荐

