Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

實現 Android 4.4 沉浸式狀態列的三種做法

編輯:關於 Android 程式設計

Android 4.4 KitKat 引入了 FLAG_TRANSLUCENT_STATUS 與 FLAG_TRANSLUCENT_NAVIGATION,讓狀態列與導覽列可以半透明,內容得以延伸到系統列的下方——這就是所謂的沉浸式效果。翻遍各大論壇再自己實測之後,可以歸納出兩條可行路線。

做法一:直接改樣式檔

建立 values-v19 資料夾(因為這個屬性從 API 19 才支援),在其中新增 styles.xml:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Toolbar(ActionBar)顏色 -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!-- 狀態列顏色 -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <!-- Toolbar 標題顏色 -->
    <item name="android:textColorPrimary">@color/white</item>
    <!-- 視窗背景色 -->
    <item name="android:windowBackground">@color/colorPrimary</item>

    <!-- 半透明系統列 -->
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

原始範例中 colorPrimaryDark 誤寫成與 colorPrimary 同值,實作時記得改成真正想用的深色。

做法二:使用 SystemBarTint 開源庫

如果你需要自訂狀態列與導覽列的填色(而不只是半透明),SystemBarTintManager 是個方便的選擇。

步驟一:加入依賴

implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'

步驟二:在 Activity 的 onCreate() 中呼叫

/** 套用 KitKat 以上的半透明效果 */
private void applyKitKatTranslucency() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setTranslucentStatus(true);

        SystemBarTintManager mTintManager = new SystemBarTintManager(this);
        mTintManager.setStatusBarTintEnabled(true);
        mTintManager.setNavigationBarTintEnabled(true);
        mTintManager.setTintDrawable(
                UIElementsHelper.getGeneralActionBarBackground(this));
    }
}

@TargetApi(19)
private void setTranslucentStatus(boolean on) {
    Window win = getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

別忘了這個關鍵屬性

不論用哪種做法,主版面配置的最外層必須加上:

android:fitsSystemWindows="true"

少了這一行,系統會認為你的內容不該延伸到系統列下方,狀態列就會維持白色,前面做的設定等於白費。

現代寫法的對照

這些技巧在當年很先進,但今天有幾點值得注意:

  • API 21 之後有更完整的方案。Lollipop 提供了 Window.setStatusBarColor() 與 setNavigationBarColor(),可以直接指定顏色,不必再靠 SystemBarTint 這種反射手法。配合 styles.xml 裡的 android:statusBarColor 更乾脆。
  • API 23 加入了 Light Status Bar。用 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 可讓狀態列圖示變深色,白底時才看得清楚。
  • API 30 全面改版。新的邊到邊(edge-to-edge)API 用 WindowInsetsController 取代了大量 systemUiVisibility 旗標,舊旗標已被標記為過時。
  • SystemBarTint 已停止維護。新專案請直接用平台 API 或 WindowInsetsCompat。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved