萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 螢幕旋轉監聽與配置變更處理詳解

配置變更與 Activity 重建機制

當裝置發生配置變更(螢幕旋轉、語言切換、字體縮放、鍵盤彈出等)時,Android 預設會銷毀並重建 Activity。這會導致:

  • 圖片被拉伸變形(橫向佈局套用直向資源)
  • 動畫中斷、執行緒邏輯錯亂
  • 使用者輸入內容丟失(若未正確保存)

解決方案對比

  • 大多數應用
  • 程式碼簡單
  • 自動套用新資源
  • 遊戲、相機、影片播放
  • 避免重建開銷
  • 需手動處理所有資源切換
  • 強制直向/橫向應用
  • 完全避免旋轉問題
  • 方案適用場景優點缺點
    預設重建 + Bundle/ViewModel 需正確處理狀態保存
    android:configChanges + onConfigurationChanged
    固定螢幕方向 使用者體驗受限

    方案一:攔截配置變更(android:configChanges)

    在 AndroidManifest.xml 中宣告 Activity 處理特定配置變更:

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
        android:label="@string/app_name">
    </activity>
    

    關鍵屬性說明:

    • orientation:螢幕方向變更(API 13+ 需配合 screenSize)
    • screenSize:螢幕尺寸變更(API 13+ 必加,否則旋轉仍會重建)
    • screenLayout:螢幕佈局變更(如分割畫面模式)
    • keyboardHidden:鍵盤顯示/隱藏
    • locale、fontScale、uiMode:語言、字體、UI 模式變更

    onConfigurationChanged 完整實作範例

    public class GameActivity extends AppCompatActivity {
        private static final String TAG = "GameActivity";
        private GameView gameView;
        private ImageView backgroundImage;
        private boolean isLandscape = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_game);
            
            gameView = findViewById(R.id.game_view);
            backgroundImage = findViewById(R.id.background_image);
            
            // 初始載入對應方向資源
            updateResourcesForOrientation(getResources().getConfiguration().orientation);
        }
    
        @Override
        public void onConfigurationChanged(@NonNull Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            
            int orientation = newConfig.orientation;
            Log.d(TAG, "Configuration changed: " + (orientation == Configuration.ORIENTATION_LANDSCAPE ? "LANDSCAPE" : "PORTRAIT"));
            
            // 1. 更新方向旗標
            boolean newIsLandscape = (orientation == Configuration.ORIENTATION_LANDSCAPE);
            if (newIsLandscape != isLandscape) {
                isLandscape = newIsLandscape;
                
                // 2. 手動切換佈局資源(如需完全不同佈局)
                // setContentView(R.layout.activity_game_land); // 謹慎使用,會重置 View 狀態
                
                // 3. 更新特定資源(圖片、尺寸、文字)
                updateResourcesForOrientation(orientation);
                
                // 4. 通知自訂 View 重新測量/繪製
                gameView.onOrientationChanged(isLandscape);
            }
            
            // 5. 處理其他配置變更
            if (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) {
                // 軟鍵盤彈出,調整遊戲區域
                gameView.adjustForKeyboard(true);
            } else if (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_YES) {
                gameView.adjustForKeyboard(false);
            }
        }
    
        private void updateResourcesForOrientation(int orientation) {
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                // 載入橫向專用資源
                backgroundImage.setImageResource(R.drawable.bg_landscape);
                // 調整遊戲畫面比例
                gameView.setAspectRatio(16f/9f);
            } else {
                // 載入直向專用資源
                backgroundImage.setImageResource(R.drawable.bg_portrait);
                gameView.setAspectRatio(9f/16f);
            }
        }
    }
    

    方案二:雙佈局資源策略(推薦大多數應用)

    建立兩套佈局檔案,讓系統自動選擇:

    res/
    ├── layout/
    │   ├── activity_main.xml          # 直向預設佈局
    │   └── activity_main.xml (land)   # 橫向佈局(在 layout-land 目錄)
    ├── layout-land/
    │   └── activity_main.xml          # 橫向專用佈局
    ├── values/
    │   ├── dimens.xml                 # 直向尺寸
    │   └── strings.xml
    └── values-land/
        └── dimens.xml                 # 橫向尺寸(如較大邊距、字體)
    

    範例 layout/activity_main.xml(直向):

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="@dimen/spacing_medium">
        
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/welcome"
            android:textSize="@dimen/text_large" />
        
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
    

    範例 layout-land/activity_main.xml(橫向):

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="@dimen/spacing_medium">
        
        <fragment
            android:id="@+id/master_fragment"
            android:name="com.example.MasterFragment"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        
        <FrameLayout
            android:id="@+id/detail_container"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2" />
    </LinearLayout>
    

    進階:偵測旋轉動畫完成時機

    若需在旋轉動畫結束後執行邏輯(如開始錄影、校準感測器):

    public class CameraActivity extends AppCompatActivity {
        private WindowManager windowManager;
        private OrientationEventListener orientationListener;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            
            orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
                @Override
                public void onOrientationChanged(int orientation) {
                    // 粗略偵測方向變化(0, 90, 180, 270 度)
                    if (orientation == ORIENTATION_UNKNOWN) return;
                    
                    int rotation = windowManager.getDefaultDisplay().getRotation();
                    handleRotationChange(rotation);
                }
            };
            
            if (orientationListener.canDetectOrientation()) {
                orientationListener.enable();
            }
        }
    
        private void handleRotationChange(int rotation) {
            // 旋轉完成後的處理邏輯
            cameraController.setDisplayOrientation(rotation);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (orientationListener != null) {
                orientationListener.disable();
            }
        }
    }
    

    最佳實踐建議

    1. 預設採用雙佈局 + ViewModel:最省力、最穩健,自動適配分割畫面、折疊裝置
    2. 僅在效能敏感場景用 configChanges:遊戲引擎、相機預覽、即時串流
    3. 測試清單:旋轉、分割畫面、字體縮放、語言切換、鍵盤彈出、折疊/展開
    4. 避免在 onConfigurationChanged 呼叫 setContentView:會重置所有 View 狀態,失去攔截重建的意義
    copyright © 萬盛學電腦網 all rights reserved