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

Android 判斷螢幕方向:橫屏與豎屏的檢測方法

編輯:關於 Android 程式設計

在 Android 開發中,經常需要判斷當前螢幕是橫屏還是豎屏,以便做出相應的介面調整。下面是一個實用的工具類,透過 getRequestedOrientation() 結合螢幕寬高來判斷方向。

public class AndroidTools {
    /**
     * 判斷橫豎屏
     * @param activity
     * @return 1:豎 | 0:橫
     */
    public static int ScreenOrient(Activity activity) {
        int orient = activity.getRequestedOrientation();
        if (orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                && orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            WindowManager windowManager = activity.getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();
            orient = screenWidth < screenHeight
                    ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                    : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        }
        return orient;
    }
}

判斷邏輯其實很直觀:先取得應用設定的螢幕方向,如果應用沒有明確指定為橫屏或豎屏,就透過螢幕的寬度與高度進行比較。當寬度小於高度時視為豎屏,反之則為橫屏。這樣一來,即便在未指定方向的情況下,也能準確獲取目前的螢幕擺放狀態。

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