Android onConfigurationChanged用法(规避横竖屏切换导致的重新调用onCreate方法)

onConfigurationChanged的目的是为了规避横竖屏切换干掉activity而重新调用onCreate方法的问题;
有的时候,我们希望重新进入OnCreate生命周期,此时可以调用onSaveInstanceState和onRestoreInstanceState方法,可参考http://www.cnblogs.com/leavescy/p/7845921.html;
而有的时候,我们又不希望这种事情发誓,所以就要重写onConfigurationChanged方法;
1. 在AndroidManifest.xml中添加一些权限:
 <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>

2. 配置目标activity属性:
android:configChanges="orientation|screenSize">

如下所示:
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.xxx.dictionarychange">
 4 
 5     <application
 6         android:allowBackup="true"
 7         android:icon="@mipmap/ic_launcher"
 8         android:label="@string/app_name"
 9         android:roundIcon="@mipmap/ic_launcher_round"
10         android:supportsRtl="true"
11         android:theme="@style/AppTheme">
12         <activity android:name=".MainActivity"
13                   android:configChanges="orientation|screenSize">
14             <intent-filter>
15                 <action android:name="android.intent.action.MAIN" />
16 
17                 <category android:name="android.intent.category.LAUNCHER" />
18             </intent-filter>
19         </activity>
20 
21 
22     </application>
23     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>
24 
25 </manifest>

3. 最后在MainActivity.java中重写onConfigurationChanged方法,如下所示:

里面打印出来了一些日志,可以提示现在是横屏还是竖屏;

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            Log.i("LANDSCAPE = ", String.valueOf(Configuration.ORIENTATION_LANDSCAPE));
        }
        else if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            Log.i("LANDSCAPE = ", String.valueOf(Configuration.ORIENTATION_PORTRAIT));

        }
        super.onConfigurationChanged(newConfig);
    }

 






posted @ 2017-11-20 21:25  小叶子leavescy  阅读(7550)  评论(0编辑  收藏  举报