美文网首页
Compose 状态栏颜色切换Compose-get组件使用

Compose 状态栏颜色切换Compose-get组件使用

作者: 进击的小大叔 | 来源:发表于2023-03-25 16:26 被阅读0次

众所周知Compose框架特性之一就是单Activity 模式(类似Flutter 框架,在一个Activity上就可以搭建整个App)

那么问题来了在使用Compose进行页面搭建的过程中会经常遇到需要根据页面动态改变当前页面的状态栏文字颜色?

其实Compose框架中也提供了修改状态栏颜色的方法:
(1)想要在compose修改状态栏颜色需要引用官方提供的SystemUI库systemuicontroller
在build.gradle 中依赖添加

     def accompanist_version = "0.28.0"
    api "com.google.accompanist:accompanist-systemuicontroller:$accompanist_version"

(2) 在组件中使用

@Composable
fun GetPage(){
       val systemUiController = rememberSystemUiController()
       systemUiController.setStatusBarColor(statusBarColor)
       systemUiController.setNavigationBarColor(navigationBarColor)
       systemUiController.systemBarsDarkContentEnabled = darkIcons
}

看起来似乎很简单,但是在使用navigation进行页面切换的时候:

PageA(状态栏文字白色)-> PageB(状态栏文字黑色) -> PageA(状态栏文字黑色)

会发现在上面的过程中从B返回到A 状态栏文字颜色并不会自动切换为我们希望的白色而还是B的黑色。

那么我们要怎么解决这个问题呢? 答案是 SideEffect 生命周期的使用

只需要在设置状态栏颜色的代码中用 SideEffect 包裹即可实现 我们要的效果

@Composable
fun GetPage(){
 val systemUiController = rememberSystemUiController()
      SideEffect {
       systemUiController.setStatusBarColor(statusBarColor)
       systemUiController.setNavigationBarColor(navigationBarColor)
       systemUiController.systemBarsDarkContentEnabled = darkIcons
   }
}

如何快捷的在项目中使用?

引用库

    implementation "io.github.sunshaobei:satis-compose-get:1.0.0"
    implementation "io.github.sunshaobei:satis-compose-get-annotation:1.0.0"
    kapt "io.github.sunshaobei:satis-compose-get-processor:1.0.0"

作为页面的Compose函数请使用 GetPage进行包裹,若搭配Compose-get路由使用效果最佳
关于Compose-get路由的使用请参考这篇文章Compose-get路由

具体实现参照Demo

相关文章

网友评论

      本文标题:Compose 状态栏颜色切换Compose-get组件使用

      本文链接:https://www.haomeiwen.com/subject/lzdnrdtx.html