Android 实现变色状态栏

Posted by PanMin Blog on December 21, 2016

– layout: post # 使用的布局(不需要改) title: Android 实现变色状态栏 # 标题 subtitle: #副标题 date: 2016-12-21 # 时间 author: PanMin # 作者 header-img: img/post-bg-2015.jpg #这篇文章标题背景图片 catalog: true # 是否归档 tags: #标签 - Android —

首先我们得了解什么是透明状态栏以及什么是沉浸式状态栏,以及其区别,国内习惯称透明状态栏为沉浸式状态栏,但是两者是有本质区别的。

先来看看什么是沉浸式模式。

Android 4.4中,沉浸式体验得到了再次强化,提供了一种“全屏模式”(Full-screen Immersive Mode)。全屏模式又分两种,一种叫后撤式 (Lean Back),另一种叫做沉浸式(Immersive)。后撤式已经在之前的系统中被广泛使用了——当你在优酷APP中观看视频时,大部分时间手指是不会去碰屏幕的。这种情况下,虚拟键和状态栏都会自动隐藏,但当你触摸屏幕的时候,它们又会出现。而新加入的沉浸式则不太一样,在沉浸式全屏状态下,对屏幕的操作并不会唤出系统栏。想要唤出系统栏,你必须从屏幕的上/下边缘向屏幕内划入。沉浸式的全屏状态更适合游戏和阅读这样的应用。

首先应用主题

<resources>
    <style name="AppTheme" parent="@style/BaseTheme">
    </style>
    <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    </style>
</resources>

然后我们在res下新建一个values-v19的目录,代表最低API为19,新建一个style.xml,下面的代码是透明状态栏的关键

<resources>
    <style name="AppTheme" parent="@style/BaseTheme">
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style>
</resources>

我们禁用了系统的ActionBar,使用ToolBar代替,布局代码如下

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:fitsSystemWindows="true"
        ></android.support.v7.widget.Toolbar>

</LinearLayout>

在Toolbar中加入了android:fitsSystemWindows=”true”属性,这就是将布局延伸到状态栏,这时候你运行一下,会发现Toolbar上移到了状态栏的位置。上移的高度刚好是状态栏的高度。

但是我们并不想它移动到上面,只是想它状态栏和Toolbar颜色一样,要怎么做的,很简单,在代码中通过setSupportActionBar设置到ActionBar的位置即可。

Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

由于这种效果只有在4.4及以上有效,在Android 5.0上,我们的状态栏的颜色是要比Toolbar的颜色要深