當 Android 裝置螢幕旋轉時,Activity 預設會銷毀並重建,導致 onCreate 再次執行,進而觸發資料重複加載(如重複發起網路請求)。以下提供兩種常見解決方式。
在 AndroidManifest.xml 的 <activity> 標籤中加入 android:configChanges 屬性,告知系統自行處理配置變更,不重建 Activity。
<activity android:name=".Your_Activity"
android:configChanges="orientation|keyboardHidden">
</activity>
接著在 Activity 中覆寫 onConfigurationChanged,並以布林旗標控制是否執行加載邏輯:
public class Your_Activity extends ListActivity {
public static boolean onRotation = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (onRotation) {
new LoadData().execute();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onRotation = false; // 旋轉後不再重複加載
}
}
採用 Android Jetpack 的 ViewModel 儲存資料,配合 LiveData 觀察變化。ViewModel 在配置變更時存活,避免重複請求。
configChanges 時,需自行處理佈局切換(如橫向/直向不同 layout)。static 或儲存於單例中,才能在重建後保持狀態。根據專案架構選擇適合方案,即可解決旋轉導致的資料重複加載問題。