@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance(); if (data == null) {//表示不是由于Configuration改變觸發的onCreate() data = loadMyData(); } ... }
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "橫屏模式", Toast.LENGTH_SHORT).show(); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ Toast.makeText(this, "豎屏模式", Toast.LENGTH_SHORT).show(); } }
官方的Android開發文檔不建議使用這種方式處理Configuration改變: Note: Using this attribute should be avoided and used only as a last-resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change. 最佳實踐 考慮到旋轉屏幕并不是使Activity被銷毀重建的唯一因素,仍然推薦前文介紹過的方法:在onPause()里持久化Activity狀態,在onCreate()里恢復現場,可以做到一舉多得;雖然Google不推薦設置android:configChanges屬性的方式,但如果你的Activity橫向縱向共用同一個layout文件,方法3無疑是最省事的。