手動管理配置更改

如果你的應用程式在特定配置更改期間不需要更新資源,並且你有效能限制要求你避免重新啟動活動,那麼你可以宣告你的活動自己處理配置更改,這會阻止系統重新啟動活動。

但是,當你必須避免因配置更改而重新啟動時,此技術應被視為最後的手段,並且不建議用於大多數應用程式。要採用這種方法,我們必須將 android:configChanges 節點新增到 AndroidManifest.xml 中的活動 :

<activity android:name=".MyActivity"
          android:configChanges="orientation|screenSize|keyboardHidden"
          android:label="@string/app_name">

現在,當其中一個配置發生更改時,活動不會重新啟動,而是接收對 onConfigurationChanged() 的呼叫:

// Within the activity which receives these changes
// Checks the current device orientation, and toasts accordingly
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

請參閱處理更改文件。有關你可以在活動中處理哪些配置更改的更多資訊,請參閱 android:configChanges文件和 Configuration類。