【问题标题】:ViewCompat.getWindowInsetsController is deprecated - which alternative to use?不推荐使用 ViewCompat.getWindowInsetsController - 使用哪种替代方法?
【发布时间】:2022-08-08 05:52:49
【问题描述】:
更新到 Android Gradle 插件版本 7.2.2 后,Jetpack Compose 项目的默认 Theme.kt 文件会发出警告:
ViewCompat.getWindowInsetsController is deprecated
此警告来自 Project Scaffolding 期间提供的默认实现:
/* snip */
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme // <--- This triggers a deprecation warning
}
}
Documentation recommends 使用 WindowCompat.getInsetsController 代替 - 但该功能需要同时访问 view 和 window。
是否有一个简单的途径来解决这个警告而不忽略它?
标签:
android
kotlin
android-jetpack-compose
material-components-android
【解决方案1】:
Complete changes that must be done available here
if sn-p 的存在只是因为 Android Studio 中的组件预览 - 其中永远没有可用的 Activity 可以附加到!(当您实际运行应用程序时,您的 view 不会处于编辑模式 - 因此实际上仅在实际场景中运行内部语句)。
由于它在逻辑上只在实际应用程序中执行,我们可以通过假设view.context 是Activity 来进行一些强制转换来检索当前的window。如果这是一个活动,您可以访问currentWindow 属性并将其用作推荐方法的window 参数。
所以我们最终得到以下代码 - 进行了一些额外的重构以减少代码重复 - 将当前视图的上下文转换为 Activity 并进行适当的设置:
@Composable
fun YourAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = pickColorScheme(dynamicColor, darkTheme)
val view = LocalView.current
if (!view.isInEditMode) {
/* getting the current window by tapping into the Activity */
val currentWindow = (view.context as? Activity)?.window
?: throw Exception("Not in an activity - unable to get Window reference")
SideEffect {
/* the default code did the same cast here - might as well use our new variable! */
currentWindow.statusBarColor = colorScheme.primary.toArgb()
/* accessing the insets controller to change appearance of the status bar, with 100% less deprecation warnings */
WindowCompat.getInsetsController(currentWindow, view).isAppearanceLightStatusBars =
darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}