
スマートフォンを傾けて、画面を回転させるとActivityは終了され、onDestroy→onCreateがコールされます。
通常のアプリであれば、画面回転をさせたときにAcitivtyを再生成させたいことはあまりないと思います。(バグの温床にもなりそうですし…)
この記事では画面回転させてもAcitivtyを破棄/終了させずに維持する方法を紹介します。
=== 目次 ===
画面回転をしてもActivityを破棄/終了させない方法
画面回転をしてもAcitivtyを破棄/終了さえないためには、AndroidManifest.xmlにおいて、 AcitivtyタグのconfigChanges属性にorientationおよびscreeanSizeを付与させます。具体的には以下です。
AndroidManifests.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.areseiproject">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
サンプルコード内の15行目の箇所がそのコードです。その他、configChangesは色々な設定をすることができますが、そちらについては以下をご参照ください。
https://developer.android.com/guide/topics/manifest/activity-element.html