當裝置發生配置變更(螢幕旋轉、語言切換、字體縮放、鍵盤彈出等)時,Android 預設會銷毀並重建 Activity。這會導致:
| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| 預設重建 + Bundle/ViewModel | 需正確處理狀態保存 | ||
| android:configChanges + onConfigurationChanged | |||
| 固定螢幕方向 | 使用者體驗受限 |
在 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 模式變更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();
}
}
}