Jetpack Compose添加AlertDialog时出现Can't find ColorStateList错误如何解决
问题根因
该报错是由于夜间主题中android:statusBarColor使用了系统属性引用?android:attr/colorBackground,AlertDialog创建时的上下文无法正确解析该属性对应的ColorStateList,最终导致资源加载失败。
解决方案
你可以选择以下任意一种方式修复:
方案1:直接替换属性引用为实际颜色资源
将night\themes.xml中android:statusBarColor的取值修改为直接引用颜色资源,避免属性解析失败:<item name="android:statusBarColor">@color/statusBarDark</item>记得在日间主题的themes.xml中也对应修改
android:statusBarColor的取值,保证不同模式下颜色正确。方案2:为AlertDialog指定独立主题
在themes.xml中新增Dialog专属主题,覆盖statusBarColor配置:<style name="Theme.AppName.Dialog" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog"> <item name="android:statusBarColor">?attr/colorSurface</item> </style>然后修改Compose代码,在AlertDialog中指定该主题:
AlertDialog( onDismissRequest = { openDialog.value = false }, // 新增Dialog配置 properties = DialogProperties( theme = R.style.Theme_AppName_Dialog ), title = { Text(text = "Dialog Title") }, // 剩余原有配置保持不变 text = { Text("Here is a text ") }, confirmButton = { Button( onClick = { openDialog.value = false }) { Text("This is the Confirm Button") } }, dismissButton = { Button( onClick = { openDialog.value = false }) { Text("This is the dismiss Button") } } )方案3:分API版本配置statusBarColor
将android:statusBarColor的配置移动到values-v23/night/themes.xml目录下,低版本系统自动跳过该配置,避免解析异常。
内容的提问来源于stack exchange,提问作者dhvl5
相关产品推荐
相关产品推荐

