在需要根據螢幕方向調整 UI 佈局、啟用/停用特定功能(如橫屏全屏播放器)時,正確偵測目前方向至關重要。本文說明標準 API 用法、常見誤區與最佳實踐。
public boolean isPortrait(Context context) {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
public boolean isLandscape(Context context) {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
// Activity
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 橫屏邏輯:顯示全屏播放器、隱藏工具列
} else {
// 直屏邏輯:恢復標準佈局
}
}
// Fragment (需在 onCreate 設定 setRetainInstance(true) 或使用 ViewLifecycleOwner)
requireActivity().getResources().getConfiguration().orientation
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
android:label="@string/app_name">
</activity>
android:configChanges 後,Activity 不會重建,而是回呼 onConfigurationChanged(),需自行處理 UI 更新。| 錯誤做法 | 問題 | 正確做法 |
|---|---|---|
比較螢幕寬高 width > height | 多窗/分割畫面/折疊裝置下寬高關係不代表系統方向 | 使用 Configuration.orientation |
監聽 onOrientationChanged (已棄用) | 僅回呼感應器方向,不代表 UI 方向 | 使用 onConfigurationChanged 或 ViewTreeObserver.OnGlobalLayoutListener |
| 在 View 建構子中檢查方向 | Context 可能未附著,Configuration 可能為預設值 | 在 onAttachedToWindow() 或 onSizeChanged() 中檢查 |
// 取得當前視窗佈局資訊
WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
WindowInsets insets = windowMetrics.getWindowInsets();
Insets systemBars = insets.getInsets(Type.systemBars());
int width = windowMetrics.getBounds().width();
int height = windowMetrics.getBounds().height();
// 判斷視窗是否為橫向佈局 (而非螢幕物理方向)
boolean isWindowLandscape = width > height;
getResources().getConfiguration().orientation。configChanges + 覆寫 onConfigurationChanged。WindowMetrics 判斷視窗長寬比。