Android 沉浸式状态栏

过时的API
  //设置默认隐藏虚拟按键,虚拟按键显示后为半透明
    protected open fun hideNavigationBarAndFullScreen() {
        val flags: Int
        // This work only for android 4.4+
        flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // This work only for android 4.4+
            // hide navigation bar permanently in android activity
            // touch the screen, the navigation bar will not show
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) //虚拟按键透明
            (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                    // bar
                    or View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    or View.SYSTEM_UI_FLAG_IMMERSIVE)

            //            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            //                    | View.SYSTEM_UI_FLAG_IMMERSIVE
            //                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
        } else {
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        }
        window.decorView.systemUiVisibility = flags
    }

上面这一大堆,全都是过时的api,当然也能用

新的方法
theme
  

theme是必不可少的

window
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            window.isNavigationBarContrastEnforced = false
        }
        window.statusBarColor = Color.TRANSPARENT
        window.navigationBarColor = Color.TRANSPARENT
        WindowCompat.setDecorFitsSystemWindows(window, true)

设置状态栏颜色,设置底部导航栏颜色

setDecorFitsSystemWindows

函数就是用来替换过时的函数 setSystemUiVisibility

setDecorfitsSystemWindows的解释

/**
     * Sets whether the decor view should fit root-level content views for
     * {@link WindowInsetsCompat}.
     * 

* If set to {@code false}, the framework will not fit the content view to the insets and will * just pass through the {@link WindowInsetsCompat} to the content view. *

*

* Please note: using the {@link View#setSystemUiVisibility(int)} API in your app can * conflict with this method. Please discontinue use of {@link View#setSystemUiVisibility(int)}. *

* * @param window The current window. * @param decorFitsSystemWindows Whether the decor view should fit root-level content views for * insets. */ public static void setDecorFitsSystemWindows(@NonNull Window window, final boolean decorFitsSystemWindows) { if (Build.VERSION.SDK_INT >= 30) { Api30Impl.setDecorFitsSystemWindows(window, decorFitsSystemWindows); } else if (Build.VERSION.SDK_INT >= 16) { Api16Impl.setDecorFitsSystemWindows(window, decorFitsSystemWindows); } }

可以看到函数内部已经做了版本适配

效果

Android 沉浸式状态栏_第1张图片Android 沉浸式状态栏_第2张图片

分别是有导航栏和无导航栏的沉浸式效果

你可能感兴趣的:(android)