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

Android 沉浸式狀態欄的兩種做法

編輯:關於 Android 程式設計

透明狀態欄是 API 19(Android 4.4)之後才有的能力,低版本並不支援。實作上大致分成兩條路:直接在程式碼裡加旗標,或是在主題樣式中宣告。

做法一:透過 Window 旗標

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // 透明狀態欄
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    // 透明導覽欄
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}

這樣寫的副作用是:視圖會被系統狀態欄的高度往上推,導致版面被遮掉一塊。解法是在配置檔中補上兩個屬性:

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:clipToPadding="true"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
</RelativeLayout>

android:fitsSystemWindows:決定配置時是否要把系統視窗(例如狀態欄)的高度計算進去。設為 true 時,系統會自動調整可用區域,讓自訂版面避開狀態欄——這正是自訂標題欄時常見的需求。

android:clipToPadding:控制 ViewGroup 是否允許在 padding 區域內繪製子檢視,預設為 true(不允許)。

做法二:直接換主題

系統內建了三組現成的半透明裝飾主題,任選其一即可:

android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar.TranslucentDecor"
android:theme="@android:style/Theme.Holo.Light.NoActionBar.TranslucentDecor"
android:theme="@android:style/Theme.Holo.NoActionBar.TranslucentDecor"

若你使用自訂主題,則在 values-19 目錄下的樣式中補上兩個項目,讓它只在 API 19 以上生效:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- API 19 的主題客製化 -->
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

兩種做法效果相近,差別在於彈性:旗標方式可以對單一 Activity 動態開關,主題方式則一次套用到整個視窗,較為省事。

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