@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance(); if (data == null) {//表示不是由于Configuration改變觸發(fā)的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開發(fā)文檔不建議使用這種方式處理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. 最佳實(shí)踐 考慮到旋轉(zhuǎn)屏幕并不是使Activity被銷毀重建的唯一因素,仍然推薦前文介紹過的方法:在onPause()里持久化Activity狀態(tài),在onCreate()里恢復(fù)現(xiàn)場,可以做到一舉多得;雖然Google不推薦設(shè)置android:configChanges屬性的方式,但如果你的Activity橫向縱向共用同一個layout文件,方法3無疑是最省事的。