預設情況下,螢幕旋轉會銷毀並重建 Activity (onDestroy → onCreate)。若需**自行處理旋轉不重建**,必須在 Manifest 宣告 configChanges 並覆寫 onConfigurationChanged()。
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden">
</activity>
關鍵值:
orientation:螢幕方向變化screenSize:API 13+ 必加,否則旋轉仍會重建keyboardHidden:鍵盤彈出/收起 (可選)@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// 取得當前方向
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 📱 橫屏邏輯
Log.d("Rotation", "切換至橫屏");
// 例:切換佈局、調整 View 可見性、暫停/恢復視頻
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
// 📱 直屏邏輯
Log.d("Rotation", "切換至直屏");
}
// 注意:ORIENTATION_UNDEFINED 罕見,可忽略
}
int newWidth = newConfig.screenWidthDp;
int newHeight = newConfig.screenHeightDp;
int smallestWidth = newConfig.smallestScreenWidthDp; // 較短邊 dp,適配平板/手機
screenSize:API 13+ 僅加 orientation 仍會重建。android:screenOrientation),則不會觸發。binding = ...inflate() 或改用 ViewStub 延遲載入。若採用 ViewModel,旋轉重建**不會銷毀 ViewModel**,資料自動保留。只需在 XML 使用 tools:orientation 預覽,無需 configChanges,減少 Bug 面。建議新專案優先採用此架構。
adb shell settings put system accelerometer_rotation 1 開啟自動旋轉。