Jetpack Compose中MediaRouteButton实现崩溃:背景不可半透明异常
问题原因
CastButtonFactory.setUpMediaRouteButton初始化按钮时会校验背景是否半透明,若检测到半透明背景就抛出异常。你之前的代码是先设置背景再执行初始化,初始化过程中可能会重置按钮背景为主题默认的半透明样式,导致触发报错。
解决方案
1. 调整代码执行顺序
先调用初始化方法,再设置按钮背景,避免初始化覆盖你的手动设置:
@Composable fun MyApp() { Column(Modifier.fillMaxSize()) { AndroidView( modifier = Modifier, factory = { ctx -> val themedContext = ContextThemeWrapper(ctx, R.style.AppTheme) val button = MediaRouteButton(themedContext) // 先完成按钮初始化 CastButtonFactory.setUpMediaRouteButton(themedContext, button) // 再设置不透明背景 button.setBackgroundColor(ctx.getColor(android.R.color.black)) button }, update = { button -> button.performClick() } ) } }
2. 通过主题直接定义按钮样式(更稳妥)
在styles.xml中为主题指定自定义的MediaRouteButton样式,确保背景默认是不透明的:
<!-- 你的App主题 --> <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <!-- 其他主题属性 --> <item name="mediaRouteButtonStyle">@style/CustomMediaRouteButton</item> </style> <!-- 自定义MediaRouteButton样式 --> <style name="CustomMediaRouteButton" parent="Widget.MediaRouter.Light.MediaRouteButton"> <item name="android:background">@android:color/black</item> <!-- 可按需添加其他样式,比如图标颜色 --> <item name="mediaRouteButtonTint">@android:color/white</item> </style>
之后代码中无需手动设置背景,直接使用主题上下文创建按钮即可。
3. 改用setBackgroundResource设置背景
如果还是有问题,尝试用资源方式设置背景,避免潜在的alpha通道问题:
button.setBackgroundResource(android.R.color.black)
内容的提问来源于stack exchange,提问作者Scoobs
相关产品推荐
相关产品推荐

