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

讓狀態欄顏色與 App 主題一致:Android 沉浸式狀態欄實作指南

編輯:關於 Android 程式設計

iOS 應用的狀態欄顏色能和標題欄保持一致,視覺整體感很強。Android 在 4.4 之前做不到,但 4.4 之後系統開放給開發者自定義狀態欄背景色,這個體驗就補上了。裝了新版 QQ 且系統在 4.4 以上的同學,可以直接看它的效果。

兩種實現路徑

路徑一:在主題或 style 中聲明

 Theme.Holo.Light.NoActionBar.TranslucentDecor
Theme.Holo.NoActionBar.TranslucentDecor

<style name="AppTheme" parent="AppBaseTheme">
 <!-- Status Bar -->
 <item name="android:windowTranslucentStatus">true</item>
 <!-- Navigation Bar -->
 <item name="android:windowTranslucentNavigation">true</item>
</style>

考慮到市面上機型系統版本差異很大,這種全局改主題的做法並不推薦。

路徑二:在代碼中控制(推薦)

建議抽一個 BaseActivity 統一處理,在 onCreate 中判斷版本後開啟透明狀態欄並上色:

 @Override protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
   setTranslucentStatus(true);
   SystemBarTintManager tintManager = new SystemBarTintManager(this);
   tintManager.setStatusBarTintEnabled(true);
   tintManager.setStatusBarTintResource(R.color.top_bg_color); // 通知欄所需顏色
  }
  setContentView(R.layout.main_activity);
 }

 @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);
 }

這裡有個容易踩的坑:setStatusBarTintResource(R.color.top_bg_color) 傳入的顏色必須寫在 color.xml 中,直接寫 Color.parseColor 會報錯。

SystemBarTintManager 源碼

這個類來自開源項目 SystemBarTint,複製進項目即可使用。

 import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
import java.lang.reflect.Method;

/**
 * Class to manage status and navigation bar tint effects
 * when using KitKat translucent system UI modes.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SystemBarTintManager {
 static {
  // Android 允許通過系統屬性覆寫是否存在導航欄,模擬器會用到
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
   try {
    Class c = Class.forName("android.os.SystemProperties");
    Method m = c.getDeclaredMethod("get", String.class);
    m.setAccessible(true);
    sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
   } catch (Throwable e) {
    sNavBarOverride = null;
   }
  }
 }

 /** The default system bar tint color value. */
 public static final int DEFAULT_TINT_COLOR = 0x99000000;

 private static String sNavBarOverride;
 private final SystemBarConfig mConfig;
 private boolean mStatusBarAvailable;
 private boolean mNavBarAvailable;
 private boolean mStatusBarTintEnabled;
 private boolean mNavBarTintEnabled;
 private View mStatusBarTintView;
 private View mNavBarTintView;

 /**
  * Constructor. Call this in the host activity onCreate method
  * after its content view has been set.
  */
 @TargetApi(19) public SystemBarTintManager(Activity activity) {
  Window win = activity.getWindow();
  ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
   // check theme attrs
   int[] attrs = {android.R.attr.windowTranslucentStatus,
     android.R.attr.windowTranslucentNavigation};
   TypedArray a = activity.obtainStyledAttributes(attrs);
   try {
    mStatusBarAvailable = a.getBoolean(0, false);
    mNavBarAvailable = a.getBoolean(1, false);
   } finally {
    a.recycle();
   }
   // check window flags
   WindowManager.LayoutParams winParams = win.getAttributes();
   int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
   if ((winParams.flags & bits) != 0) mStatusBarAvailable = true;
   bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
   if ((winParams.flags & bits) != 0) mNavBarAvailable = true;
  }
  mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
  // device might not have virtual navigation keys
  if (!mConfig.hasNavigtionBar()) mNavBarAvailable = false;

  if (mStatusBarAvailable) setupStatusBarView(activity, decorViewGroup);
  if (mNavBarAvailable) setupNavBarView(activity, decorViewGroup);
 }

 /** Enable tinting of the system status bar. */
 public void setStatusBarTintEnabled(boolean enabled) {
  mStatusBarTintEnabled = enabled;
  if (mStatusBarAvailable) {
   mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
  }
 }

 /** Enable tinting of the system navigation bar. */
 public void setNavigationBarTintEnabled(boolean enabled) {
  mNavBarTintEnabled = enabled;
  if (mNavBarAvailable) {
   mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
  }
 }

 /** Apply the specified color tint to all system UI bars. */
 public void setTintColor(int color) {
  setStatusBarTintColor(color);
  setNavigationBarTintColor(color);
 }

 /** Apply the specified drawable or color resource to all system UI bars. */
 public void setTintResource(int res) {
  setStatusBarTintResource(res);
  setNavigationBarTintResource(res);
 }

 /** Apply the specified drawable to all system UI bars. */
 public void setTintDrawable(Drawable drawable) {
  setStatusBarTintDrawable(drawable);
  setNavigationBarTintDrawable(drawable);
 }

 /** Apply the specified alpha to all system UI bars. */
 public void setTintAlpha(float alpha) {
  setStatusBarAlpha(alpha);
  setNavigationBarAlpha(alpha);
 }

 /** Apply the specified color tint to the system status bar. */
 public void setStatusBarTintColor(int color) {
  if (mStatusBarAvailable) mStatusBarTintView.setBackgroundColor(color);
 }

 /** Apply the specified drawable or color resource to the system status bar. */
 public void setStatusBarTintResource(int res) {
  if (mStatusBarAvailable) mStatusBarTintView.setBackgroundResource(res);
 }

 /** Apply the specified drawable to the system status bar. */
 @SuppressWarnings("deprecation")
 public void setStatusBarTintDrawable(Drawable drawable) {
  if (mStatusBarAvailable) mStatusBarTintView.setBackgroundDrawable(drawable);
 }

 /** Apply the specified alpha to the system status bar. */
 @TargetApi(11) public void setStatusBarAlpha(float alpha) {
  if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
   mStatusBarTintView.setAlpha(alpha);
  }
 }

 /** Apply the specified color tint to the system navigation bar. */
 public void setNavigationBarTintColor(int color) {
  if (mNavBarAvailable) mNavBarTintView.setBackgroundColor(color);
 }

 /** Apply the specified drawable or color resource to the system navigation bar. */
 public void setNavigationBarTintResource(int res) {
  if (mNavBarAvailable) mNavBarTintView.setBackgroundResource(res);
 }

 /** Apply the specified drawable to the system navigation bar. */
 @SuppressWarnings("deprecation")
 public void setNavigationBarTintDrawable(Drawable drawable) {
  if (mNavBarAvailable) mNavBarTintView.setBackgroundDrawable(drawable);
 }

 /** Apply the specified alpha to the system navigation bar. */
 @TargetApi(11) public void setNavigationBarAlpha(float alpha) {
  if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
   mNavBarTintView.setAlpha(alpha);
  }
 }

 public SystemBarConfig getConfig() { return mConfig; }
 public boolean isStatusBarTintEnabled() { return mStatusBarTintEnabled; }
 public boolean isNavBarTintEnabled() { return mNavBarTintEnabled; }

 private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
  mStatusBarTintView = new View(context);
  LayoutParams params = new LayoutParams(
    LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
  params.gravity = Gravity.TOP;
  if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
   params.rightMargin = mConfig.getNavigationBarWidth();
  }
  mStatusBarTintView.setLayoutParams(params);
  mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
  mStatusBarTintView.setVisibility(View.GONE);
  decorViewGroup.addView(mStatusBarTintView);
 }

 private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
  mNavBarTintView = new View(context);
  LayoutParams params;
  if (mConfig.isNavigationAtBottom()) {
   params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
   params.gravity = Gravity.BOTTOM;
  } else {
   params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
   params.gravity = Gravity.RIGHT;
  }
  mNavBarTintView.setLayoutParams(params);
  mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
  mNavBarTintView.setVisibility(View.GONE);
  decorViewGroup.addView(mNavBarTintView);
 }

 /**
  * Class which describes system bar sizing and other characteristics
  * for the current device configuration.
  */
 public static class SystemBarConfig {
  private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
  private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
  private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
  private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
  private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";

  private final boolean mTranslucentStatusBar;
  private final boolean mTranslucentNavBar;
  private final int mStatusBarHeight;
  private final int mActionBarHeight;
  private final boolean mHasNavigationBar;
  private final int mNavigationBarHeight;
  private final int mNavigationBarWidth;
  private final boolean mInPortrait;
  private final float mSmallestWidthDp;

  private SystemBarConfig(Activity activity, boolean translucentStatusBar,
    boolean traslucentNavBar) {
   Resources res = activity.getResources();
   mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
   mSmallestWidthDp = getSmallestWidthDp(activity);
   mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
   mActionBarHeight = getActionBarHeight(activity);
   mNavigationBarHeight = getNavigationBarHeight(activity);
   mNavigationBarWidth = getNavigationBarWidth(activity);
   mHasNavigationBar = (mNavigationBarHeight > 0);
   mTranslucentStatusBar = translucentStatusBar;
   mTranslucentNavBar = traslucentNavBar;
  }

  @TargetApi(14) private int getActionBarHeight(Context context) {
   int result = 0;
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    TypedValue tv = new TypedValue();
    context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
    result = TypedValue.complexToDimensionPixelSize(
      tv.data, context.getResources().getDisplayMetrics());
   }
   return result;
  }

  @TargetApi(14) private int getNavigationBarHeight(Context context) {
   Resources res = context.getResources();
   int result = 0;
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    if (hasNavBar(context)) {
     String key = mInPortrait ? NAV_BAR_HEIGHT_RES_NAME : NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
     return getInternalDimensionSize(res, key);
    }
   }
   return result;
  }

  @TargetApi(14) private int getNavigationBarWidth(Context context) {
   Resources res = context.getResources();
   int result = 0;
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    if (hasNavBar(context)) {
     return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
    }
   }
   return result;
  }

  @TargetApi(14) private boolean hasNavBar(Context context) {
   Resources res = context.getResources();
   int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
   if (resourceId != 0) {
    boolean hasNav = res.getBoolean(resourceId);
    // check override flag
    if ("1".equals(sNavBarOverride)) hasNav = false;
    else if ("0".equals(sNavBarOverride)) hasNav = true;
    return hasNav;
   } else {
    return !ViewConfiguration.get(context).hasPermanentMenuKey();
   }
  }

  private int getInternalDimensionSize(Resources res, String key) {
   int result = 0;
   int resourceId = res.getIdentifier(key, "dimen", "android");
   if (resourceId > 0) result = res.getDimensionPixelSize(resourceId);
   return result;
  }

  @SuppressLint("NewApi") private float getSmallestWidthDp(Activity activity) {
   DisplayMetrics metrics = new DisplayMetrics();
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
   } else {
    // 4.4 以下不精確,但這裡並不介意
    activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
   }
   float widthDp = metrics.widthPixels / metrics.density;
   float heightDp = metrics.heightPixels / metrics.density;
   return Math.min(widthDp, heightDp);
  }

  /** 導航欄是否出現在屏幕底部 */
  public boolean isNavigationAtBottom() {
   return (mSmallestWidthDp >= 600 || mInPortrait);
  }

  public int getStatusBarHeight() { return mStatusBarHeight; }
  public int getActionBarHeight() { return mActionBarHeight; }
  public boolean hasNavigtionBar() { return mHasNavigationBar; }
  public int getNavigationBarHeight() { return mNavigationBarHeight; }
  public int getNavigationBarWidth() { return mNavigationBarWidth; }

  /** 頂部系統 UI 佔用的布局內縮量 */
  public int getPixelInsetTop(boolean withActionBar) {
   return (mTranslucentStatusBar ? mStatusBarHeight : 0)
     + (withActionBar ? mActionBarHeight : 0);
  }

  public int getPixelInsetBottom() {
   if (mTranslucentNavBar && isNavigationAtBottom()) return mNavigationBarHeight;
   else return 0;
  }

  public int getPixelInsetRight() {
   if (mTranslucentNavBar && !isNavigationAtBottom()) return mNavigationBarWidth;
   else return 0;
  }
 }
} 

源碼出處:https://github.com/jgilfelt/SystemBarTint

效果與一個關鍵屬性

仔細看會發現標題欄被頂上去了——界面變成了全屏,狀態欄蓋在內容之上。這顯然不是我們想要的。解法很簡單,在 Activity 布局文件的最外層控件上加一個屬性:

android:fitsSystemWindows="true"

踩坑記錄:TabActivity 場景

以上方案對單個 Activity 有效,但遇到 TabActivity 結構就會出問題。假設 MainActivity 繼承 TabActivity,下掛 Tab1、Tab2、Tab3 三個子 Activity:設置狀態欄的代碼寫在 MainActivity,而 android:fitsSystemWindows="true" 要寫在三個子 Activity 的布局裡。結果是首頁 Tab1 正常,Tab2 和 Tab3 卻相當於沒加這個屬性。

一開始懷疑是 Activity 順序問題,把 Tab1 和 Tab3 調換位置後,變成新的首頁正常、原首頁不正常。最後採用的繞過辦法是:在子 Activity 的 onCreate 裡手動給最外層容器加上一段 padding:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  ((LinearLayout) findViewById(R.id.ll))
    .setPadding(0, SysUtils.getStatusHeight(this), 0, 0);
 }

思路是先算出狀態欄高度,再把最外層控件的 paddingTop 撐開這麼多,效果剛好對上。

狀態欄高度的取法

 /**
  * 狀態欄高度算法
  * @param activity
  * @return
  */
 public static int getStatusHeight(Activity activity) {
  int statusHeight = 0;
  Rect localRect = new Rect();
  activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
  statusHeight = localRect.top;
  if (0 == statusHeight) {
   Class<?> localClass;
   try {
    localClass = Class.forName("com.android.internal.R$dimen");
    Object localObject = localClass.newInstance();
    int i5 = Integer.parseInt(
      localClass.getField("status_bar_height").get(localObject).toString());
    statusHeight = activity.getResources().getDimensionPixelSize(i5);
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    e.printStackTrace();
   } catch (InstantiationException e) {
    e.printStackTrace();
   } catch (NumberFormatException e) {
    e.printStackTrace();
   } catch (IllegalArgumentException e) {
    e.printStackTrace();
   } catch (SecurityException e) {
    e.printStackTrace();
   } catch (NoSuchFieldException e) {
    e.printStackTrace();
   }
  }
  return statusHeight;
 }

這段代碼先用 getWindowVisibleDisplayFrame 拿可見區域頂部,取不到時再反射讀系統的 status_bar_height 尺寸資源兜底。兩層保險之下,絕大部分機型都能拿到正確數值。

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