Android重写onConfigurationChanged规避横竖屏切换时候重新进入onCreate生命周期
Android系统内在的机制,当activity在横竖屏切换时候,会强制重新开始进入activity的生命周期onCreate,在有些特殊的场景,开发者不希望重新进入onCreate生命周期,那么,可以通过重写Android的onConfigurationChanged规避。
具体做法:
(1)添加权限:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses
(2)因为需要在activity里面检测横竖屏幕的切换变化,故而在Androidmanifest.xml里面配置目标activity的属性:
android:configChanges="orientation|screenSize"
至此,完整的Androidmanifest.xml文件:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="zhangphil.config" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:configChanges="orientation|screenSize" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" > </uses-permission> </manifest>
(3)接下来就是重写activity里面的onConfigurationChanged:
@Override public void onConfigurationChanged(Configuration newConfig) { if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 当前为横屏 Log.d(tag, "ORIENTATION_LANDSCAPE=" + Configuration.ORIENTATION_LANDSCAPE);// 2 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 当前为竖屏 Log.d(tag, "ORIENTATION_PORTRAIT=" + Configuration.ORIENTATION_PORTRAIT);// 1 } super.onConfigurationChanged(newConfig); }
完整的测试MainActivity.java代码文件:
package zhangphil.config; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class MainActivity extends Activity { private final String tag = "zhangphil"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(this, "onCreate @ " + System.currentTimeMillis(), Toast.LENGTH_SHORT).show(); } @Override public void onConfigurationChanged(Configuration newConfig) { if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 当前为横屏 Log.d(tag, "ORIENTATION_LANDSCAPE=" + Configuration.ORIENTATION_LANDSCAPE);// 2 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 当前为竖屏 Log.d(tag, "ORIENTATION_PORTRAIT=" + Configuration.ORIENTATION_PORTRAIT);// 1 } super.onConfigurationChanged(newConfig); } }