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)
    }

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/125683673