android状态栏透明代码(android设置状态栏颜色)

对于android来说什么是沉浸式状态栏?给个图你对比看就懂了:

非沉浸式

沉浸式

对比上面两张照片后,沉浸式和非沉浸式状态栏的区别就出来了,当然沉浸式状态栏还有其他种类。比如像你在玩游戏的时候,你如果没有在状态栏的位置下拉,状态栏是不会出来的,这种也是常用的沉浸式状态栏一种。

好,了解完沉浸式状态栏和非沉浸式状态栏的区别后,我们现在开始真正地去实现它。

首先,我们要先去判断我们的android版本,如果是大于5.0,我们就适配我们的沉浸式状态栏。接着,我们需要获取我们最上层的view来进行操作,android顶层的view是window,所以我们先获取window,然后去设置我们的systemuivisibility为全屏且需要状态栏,当然别忘了设置statusbar为透明。代码如下:

class mainactivity : appcompatactivity() {
    override fun oncreate(savedinstancestate: bundle?) {
        super.oncreate(savedinstancestate)
        setcontentview(r.layout.activity_main)

        //判断android的版本是否大于5.0
        if (build.version.sdk_int >= build.version_codes.lollipop){

            //获取最上层的view进行操作
            window.decorview.systemuivisibility = view.system_ui_flag_layout_fullscreen
                    .or(view.system_ui_flag_layout_stable)

            window.statusbarcolor = color.transparent//透明
        }
    }
}

还有,我们需要在androidmanifest文件下设置我们activity的主题为noactionbar,代码如下:

  <activity android:name=".mainactivity"
            android:theme="@style/theme.appcompat.light.noactionbar">
            <intent-filter>
                <action android:name="android.intent.action.main" />

                <category android:name="android.intent.category.launcher" />
            </intent-filter>
        </activity>

最后贴一下我的xml布局文件的代码,方便小白阅读实现:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mainactivity">

  <linearlayout
      android:background="@color/coloraccent"
      android:layout_height="match_parent"
      android:layout_width="match_parent"/>
>
</androidx.constraintlayout.widget.constraintlayout>

这样我们的沉浸式的状态栏就实现了,这是我们第一种实现方式,那么如果想实现游戏全屏沉浸式状态栏又该怎么样做呢?别急,我早有准备,我们其他代码不改,在我们的systemuivisibility的设置项中参考以下代码,添加上去就能轻松实现。这个时候,我们的导航栏和状态栏都被隐藏了,只有在拉下的情况会出现,过一段时间又会自动地缩回去。

       window.decorview.systemuivisibility = view.system_ui_flag_layout_fullscreen
                    .or(view.system_ui_flag_layout_stable)
                    .or(view.system_ui_flag_layout_hide_navigation)
                    .or(view.system_ui_flag_hide_navigation)
                    .or(view.system_ui_flag_fullscreen)
                    .or(view.system_ui_flag_immersive_sticky)

这样我们的沉浸式状态栏就轻松地实现好了,如果有什么不对的地方,欢迎大家指出一起探讨哦!

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐