Android Compose 沉浸式状态栏

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Compose 沉浸式状态栏相关的知识,希望对你有一定的参考价值。

官方文档
Guide - Accompanist

已经废弃了 但是要使用

WindowCompat.setDecorFitsSystemWindows(window, false)

所以我们使用这个库

https://google.github.io/accompanist/systemuicontr

onCreate当中 完整代码

        WindowCompat.setDecorFitsSystemWindows(window, false)

        val statusBarHeight = StatusBarUtil.getStatusBarHeightByDp(this)
        setContent 
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(top = statusBarHeight.dp)
            ) 

                    You code
            


            val systemUiController = rememberSystemUiController()
            SideEffect 
                // Update all of the system bar colors to be transparent, and use
                // dark icons if we're in light theme
                systemUiController.setSystemBarsColor(
                    color = androidx.compose.ui.graphics.Color.Transparent,
//                    color = Companion.Black,
                    darkIcons = true
                )


            
        

https://google.github.io/accompanist/systemuicontr

添加依赖

    //沉浸式状态栏
    api "com.google.accompanist:accompanist-systemuicontroller:0.23.1"

使用

            val systemUiController = rememberSystemUiController()
            val useDarkIcons = MaterialTheme.colors.isLight
            SideEffect 
                // Update all of the system bar colors to be transparent, and use
                // dark icons if we're in light theme
                systemUiController.setSystemBarsColor(
                    color = androidx.compose.ui.graphics.Color.Transparent,
                    darkIcons = useDarkIcons
                )

                // setStatusBarsColor() and setNavigationBarColor() also exist
            

完整代码

    //获取状态栏高度
    fun getStatusBarHeight(context: Context): Int 
        var result: Int = 0
        val resourceId: Int = context.getResources().getIdentifier(
            "status_bar_height", "dimen", "android"
        )
        if (resourceId > 0) 
            result = context.getResources().getDimensionPixelSize(resourceId)
        
        return result
    

    fun getStatusBarHeightByDp(context: Context): Int 
        val px=getStatusBarHeight(context)
        val statusBarHeight = ScreenUtil.px2dp(px)
        return statusBarHeight
    
    /**
     * px转换为dp值
     *
     * @param context 应用程序上下文
     * @param pxValue px值
     * @return 转换后的dp值
     */
    fun px2dp(context: Context, pxValue: Int): Int 
        return (pxValue / getDensity(context) + 0.5f).toInt()
    

    fun px2dp(dpValue: Int): Int 
        return px2dp(HaiveApplication.gContext, dpValue)
    

以上是关于Android Compose 沉浸式状态栏的主要内容,如果未能解决你的问题,请参考以下文章

Android 沉浸式状态栏

Android 实现沉浸式状态栏

Android状态栏着色(非沉浸式状态栏)

android -------- 沉浸式状态栏和沉浸式导航栏(ImmersionBar)

Android---沉浸式状态栏

android沉浸式