Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 沉浸式狀態欄實戰:讓狀態欄換上你要的顏色

編輯:Android 開發實例

一、概述

近來注意到新版 QQ 採用了沉浸式狀態欄的設計。先說結論,本篇要達成的效果如下圖:

關於這個「狀態欄變色」到底該叫 Immersive Mode 還是 Translucent Bars,有興趣的讀者可以自行查閱資料,這裡我們直接進入實作。

先講清楚前提:只有 4.4 以上版本才支援半透明狀態欄,而且 4.4 與 5.0 的視覺呈現存在差異。所以本篇要處理的兩件事是:

• 如何在 4.4 以上實現半透明狀態欄效果
• 如何讓 4.4 的呈現盡可能貼近 5.0

讀了不少參考文章,很多都會推薦 SystemBarTint 這個庫,有興趣可以研究。不過本篇並不依賴它,而是自己動手做了一個 hack。

二、先看效果

先把成果攤開,方便後面逐步對照。

4.4 模擬器:

5.x 真機:

三、實作半透明狀態欄

本範例使用了 NavigationView,所以版面配置程式碼稍長一些,如果你不需要,自行刪減即可。記得先引入相關依賴:

compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.0'

(一)colors.xml 與 styles.xml

先定義幾個顏色,放在 res/values/color.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#FF03A9F4</color>
    <color name="primary_dark">#FF0288D1</color>
    <color name="status_bar_color">@color/primary_dark</color>
</resources>

接著是 values/styles.xml:

<resources>
    <style name="BaseAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">#FF4081</item>
    </style>

    <style name="AppTheme" parent="@style/BaseAppTheme"></style>
</resources>

然後是 values-v19/styles.xml:

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

這裡沒什麼玄機。主題基於 NoActionBar,而 android:windowTranslucentStatus 這個屬性正是從 API 19 開始引入的,因此必須放在 values-v19 底下。

(二)版面配置

activity_main.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/id_main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/id_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:fitsSystemWindows="true"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <TextView
            android:id="@+id/id_tv_content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="HelloWorld"
            android:textSize="30sp" />
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/id_nv_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/header_just_username"
        app:menu="@menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>

結構很直觀:DrawerLayout 裡一個 LinearLayout 當內容區,一個 NavigationView 當抽屜選單。這裡有個關鍵細節——Toolbar 的高度必須設為 wrap_content。

NavigationView 另外依賴一個 header 版面配置:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="?attr/colorPrimaryDark"
    android:orientation="vertical"
    android:padding="16dp"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:id="@+id/id_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="16dp"
        android:text="https://blog.csdn.net/lmj623565791" />

    <TextView
        android:id="@+id/id_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/id_link"
        android:text="Zhang Hongyang" />

    <ImageView
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:layout_above="@id/id_username"
        android:layout_marginBottom="16dp"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

menu 的檔案就不貼了,細節可參考官方 Design Support Library 的相關說明。

看完版面配置,有三個地方務必留意:

• Toolbar 高度設為 wrap_content
• Toolbar 加上 android:fitsSystemWindows="true"
• header 版面配置的頂層 RelativeLayout 也加上 android:fitsSystemWindows="true"

android:fitsSystemWindows 的作用,是透過調整該 View 的 padding,替狀態欄空出位置。如果你不寫,狀態欄就會跟 Toolbar 擠在一起,視覺上會變成這樣:

(三)Activity 程式碼

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        setSupportActionBar(toolbar);
        // StatusBarCompat.compat(this, getResources().getColor(R.color.status_bar_color));
        // StatusBarCompat.compat(this);
    }
}

沒什麼玄機,就是 setSupportActionBar。

此時 4.4 的呈現如下:

其實還不錯,自帶一層漸層感。而 5.x 的呈現是:

可以看到 5.x 預設並不是漸層,而是一塊比 Toolbar 略深的純色。對照 Material Design 規範:

狀態欄應該要是比 Toolbar 背景色再深一點的色調。看來我們確實有必要為 4.4 補一層適配,讓它盡可能貼近 5.x 的視覺,或者說貼近 Material Design 的規範。

四、調整 4.4 的顯示方案

問題來了:要怎麼做?

換個角度想。4.4 之後我們加了 windowTranslucentStatus,這意味著狀態欄那片區域我們已經能用到了。既然能用到,那麼只要在根版面配置裡放一個與狀態欄等高的 View,把背景設成我們想要的顏色,事情就解決了。

於是我寫出了這樣一個工具類別:

public class StatusBarCompat {

    private static final int INVALID_VAL = -1;
    private static final int COLOR_DEFAULT = Color.parseColor("#20000000");

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void compat(Activity activity, int statusColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (statusColor != INVALID_VAL) {
                activity.getWindow().setStatusBarColor(statusColor);
            }
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            int color = COLOR_DEFAULT;
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            if (statusColor != INVALID_VAL) {
                color = statusColor;
            }
            View statusBarView = new View(activity);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
            statusBarView.setBackgroundColor(color);
            contentView.addView(statusBarView, lp);
        }
    }

    public static void compat(Activity activity) {
        compat(activity, INVALID_VAL);
    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}

思路非常單純:取得 Activity 的 android.R.id.content,在其中塞入一個高度等於狀態欄、背景色為指定顏色(預設是半透明黑)的 View。

使用時只要在 Activity 裡寫一行:

StatusBarCompat.compat(this);

想自訂顏色就傳入第二個參數:

StatusBarCompat.compat(this, getResources().getColor(R.color.status_bar_color));

這樣 4.4 到 5.x 的適配問題就用一行解決了,相當省事。

最後補充一點:5.0 提供了 setStatusBarColor 可以直接設定狀態欄顏色,但使用這個方法時,主題裡就不能再帶 windowTranslucentStatus 屬性。因此建議多準備一個 values-v21 資料夾,裡面的 styles.xml 寫成:

<resources>
    <style name="AppTheme" parent="@style/BaseAppTheme"></style>
</resources>

重點就是不要有 windowTranslucentStatus 這個屬性。

接著我們來驗證自訂顏色的效果,這裡挑一個紅色。4.4 模擬器:

5.x 真機:

兩邊呈現一致,收工。

完整源碼可參考:https://github.com/hongyangAndroid/ColorfulStatusBar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved