重力感應觸發旋轉 → 當前 Activity onDestroy() → onCreate() 重建 → 載入對應 layout-land/layout-port 佈局。缺點:相機預覽、影片播放、複雜表單會卡頓/黑屏/資料遺失。
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 強制橫向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 強制直向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); // 恢復感應器
onDestroy/onCreate 重建。
API 13+ 必須包含 screenSize,否則旋轉仍會重建。
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 切換橫向佈局、調整 UI
} else {
// 切換直向佈局
}
}
適用:需要精確角度、平滑動畫、不重建 Activity、相機預覽無縫旋轉。
private OrientationEventListener orientationListener;
private boolean isPortrait = true;
private void startOrientationListener() {
orientationListener = new OrientationEventListener(this) {
@Override public void onOrientationChanged(int rotation) {
// rotation: 0~359 度,0=正向直立
boolean nowPortrait = (rotation >= 315 || rotation < 45) || (rotation >= 135 && rotation < 225);
if (nowPortrait != isPortrait) {
isPortrait = nowPortrait;
onOrientationChanged(nowPortrait ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
};
orientationListener.enable(); // 開始監聽
}
protected abstract void onOrientationChanged(int orientation);
// 子類實作:切換佈局、旋轉相機預覽、調整 UI、發送事件等
@Override protected void onDestroy() {
super.onDestroy();
if (orientationListener != null) orientationListener.disable();
}
ViewModel + onSaveInstanceState 讓重建無感,最省力。ViewModel 保存 UI 狀態跨越重建。layout-land 適配橫向。CameraX 自動處理旋轉。OrientationEventListener。根據業務複雜度選擇適當方案,平衡開發成本與用戶體驗。