仿微信新版沉浸式效果,解决状态栏蒙灰,遮罩问题。

代码为Kotlin,但不影响Java开发者阅读。
isLight参数,如果为true,就将状态栏的图标和文本设置成黑色。
为false, 就变成白色。

class SystemUtil {

    companion object {

        /**
         * @param isLight  if true, set icons and text color to black.
         *                 if false, set icons and text color to white.
         */
        fun setStatusBar(window: Window, isLight: Boolean) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                if (isLight) {
                    window.clearFlags(
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                                or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                    )

                    window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
                } else {
                    window.clearFlags(
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                                or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                                or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    )
                    window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
                }

                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.statusBarColor = Color.BLACK
            }

        }
    }
}

你可能感兴趣的:(android,开发)