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

Android 開發實戰:精準取得螢幕、狀態列與標題列高度

編輯:關於 Android 程式設計

為什麼「取高度」在 Android 裡不直覺

在 Android 上做自適應版面時,經常需要知道螢幕有多高、狀態列佔了多少、標題列又吃掉多少像素。這些數值分散在不同 API 上,稍不注意就會拿到錯誤的答案——例如把「可用區域高度」誤當成「螢幕高度」。本文把常用的幾條路徑整理清楚。

方式一:直接量測既有的 View

最直觀的做法,是對已經完成佈局的 View 呼叫 getWidth() 與 getHeight()。要注意的是,只有在 onMeasure()/onLayout() 之後,或等到第一幀繪製完成,這些值才是有效的;在 onCreate() 裡立刻取值往往會得到 0。

另一條路是透過 Activity 取得系統內容根節點。Android 在繪製時,會把你要顯示的 View 掛到一個 FrameLayout 之下,這個容器可以透過 Window.ID_ANDROID_CONTENT 找到:

// 直接量測目前這個 View
int w = view.getWidth();
int h = view.getHeight();

// 透過 Activity 取得內容根容器(FrameLayout)
View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
int contentHeight = content.getHeight();

方式二:Display 與 DisplayMetrics

取得 Display 物件的方式是 getWindowManager().getDefaultDisplay(),接著用 getWidth() 與 getHeight() 分別拿到螢幕寬與螢幕高。也可以讓 Display 幫你填入 DisplayMetrics,再由 metrics 取值,本質上是同一份資料:

Display display = getWindowManager().getDefaultDisplay();

int screenWidth  = display.getWidth();   // 螢幕寬度
int screenHeight = display.getHeight();  // 螢幕高度

DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int widthPixels  = metrics.widthPixels;
int heightPixels = metrics.heightPixels;

補充一點:Canvas、Display、DisplayMetrics 三者都能取得螢幕高寬,實務上以 DisplayMetrics 最常用,因為它同時帶了 density 等資訊,方便做 dp 與 px 的換算。

狀態列高度怎麼算

decorView 是整個 Window 最上層的 View。它提供的 getWindowVisibleDisplayFrame(Rect) 會把「應用程式實際可見的區域」填進 Rect,這個區域包含標題列、但不包含狀態列。因此 Rect.top 就是狀態列高度:

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

標題列高度怎麼算

findViewById(Window.ID_ANDROID_CONTENT) 取到的是「不含標題列」的那層容器,它的 getTop() 等於狀態列加上標題列的總高度。兩者相減即可得到標題列高度:

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
// statusBarHeight 為上一步求得的狀態列高度
int titleBarHeight = contentTop - statusBarHeight;

較新的 API 怎麼寫

上述做法在早期版本上非常通用,但值得留意幾個演進:Display.getWidth()/getHeight() 在 API 30 已標記為 deprecated,官方建議改用 WindowManager.getCurrentWindowMetrics();取得狀態列與導覽列高度,較新的寫法是 View.setOnApplyWindowInsetsListener() 搭配 WindowInsets.getInsets(WindowInsets.Type.statusBars()),在全面屏、瀏海與手勢導覽列環境下更可靠。若只是要讓某個 View 延伸到狀態列下方,記得搭配 fitsSystemWindows 或自行處理 insets padding。

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