Alv*_* RC 21 android kotlin material-components-android android-jetpack-compose
更新到 Android Gradle 插件版本后,Jetpack Compose 项目的7.2.2
默认文件会出现警告:Theme.kt
ViewCompat.getWindowInsetsController is deprecated
Run Code Online (Sandbox Code Playgroud)
此警告来自项目脚手架期间提供的默认实现:
/* 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
}
}
Run Code Online (Sandbox Code Playgroud)
文档建议使用WindowCompat.getInsetsController
- 但该函数需要访问 aview
和 a window
。
是否有一种简单的方法可以解决此警告而不忽略它?
Alv*_* RC 29
该if
代码片段的存在只是因为 Android Studio 中的组件预览 - 那里永远没有可用的活动可以附加!(当您实际运行应用程序时,您view
将不会处于编辑模式 - 因此实际上仅在真实场景中运行内部语句)。
由于它在逻辑上仅在实际应用程序中执行,因此我们可以window
通过假设view.context
是一个Activity
. 如果这是一个活动,您可以访问该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
)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5429 次 |
最近记录: |