Android App 開發之橫豎屏切換

  • AndroidManifest.xml 文件對應的 Activity 屬性加入 android:screenOrientation=”sensor” 。如果不想每次切換都重新載入畫面可在 Activity 屬性裡加入 android:configChanges=”orientation|keyboardHidden”
  • res 文件夾中創建 layout-port 和 layout-land 文件夾,分別放入橫豎屏對應的佈局文件(文件名保持一致),這樣在切換時合自動調用對應的佈局。
  • Activity Java 文件中 Override onConfigurationChanged 方法用於監聽切換狀態:
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {

}
else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {

}
}
  • 在 Activity Java 文件中 Override onSaveInstanceState 方法用於數據存儲:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}

切換後 onCreate 方法被調用時可以通過 savedInstanceState 獲取已存儲的數據 或 Override onRestoreInstanceState 方法:

protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState != null){
}
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}

Activity Java 文件中也可 Override onRetainCustomNonConfigurationInstance 方法代替 onSaveInstanceState 用於數據存儲:

@Override
public Object onRetainCustomNonConfigurationInce() {
return yourObject;
}

onCreate 中獲取已存儲的數據使用 getLastNonConfigurationInstance

方法:

YourObject yourObject = getLastNonConfigurationInstance();

它的好處在於可以更快速的還原 Activity 狀態信息,可以持有原有線程,無需通過重新創建進程恢復原有狀態。

  • 橫豎屏切換時 Activity 生命週期變化:
  1. Activity 不設置 android:configChanges 時不會調用 onConfigurationChanged ,每次切換都會執行如下生命週期:
  • onPause
  • onSaveInstanceState
  • onStop
  • onRetainCustomNonConfigurationInce
  • onDestroy
  • onCreate
  • onStart
  • onRestoreInstanceState
  • onResume

2. Activity 設置 android:configChanges=”orientation|keyboardHidden”

第一次切換只調用 onConfigurationChanged ,切換回來後生命週期如下:

  • onConfigurationChanged
  • onPause
  • onSaveInstanceState
  • onStop
  • onRetainCustomNonConfigurationInstance
  • onDestroy
  • onCreate
  • onStart
  • onRestoreInstanceState
  • onResume
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.