onConfigurationChanged 不生效问题解决方案:android
1).首先,须要重写onConfigurationChanged函数app
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//do something
}ide
2). 须要在AndroidManifest.xml的Activity中配置android:configChanges参数。函数
<activity android:name=".StationListActivity"
android:configChanges="locale|layoutDirection" //4.2以后的版本中必现添加layoutDirection属性,不然onConfigurationChanged不生效。
android:windowSoftInputMode="adjustNothing"
android:screenOrientation="portrait">
</activity>字体
3)详解以下:this
API原文说明:
android:configChanges
Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.spa
Any or all of the following strings are valid values for this attribute. Multiple values are separated by '|' — for example, "locale|navigation|orientation".rest
All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change.xml
以上文档在较早版本中摘录,确少android 4.2以后的版本中的配置,须要参考最新的开发文档。必须属性layoutDirection。blog
在一些特殊的状况中,你可能但愿当一种或者多种配置改变时避免从新启动你的activity。你能够经过在manifest中设置android:configChanges属性来实现这点。
你能够在这里声明activity能够处理的任何配置改变,当这些配置改变时不会从新启动activity,而会调用activity的onConfigurationChanged(Resources.Configuration)方法。
若是改变的配置中包含了你所没法处理的配置(在android:configChanges并未声明),你的activity仍然要被从新启动,而onConfigurationChanged(Resources.Configuration)将不会被调用。
其次:android:configChanges=""中能够用的值:keyboard|mcc|mnc|locale|touchscreen|keyboardHidden|navigation|orientation……
Configuration 类中包含了不少种信息,例如系统字体大小,orientation,输入设备类型等等.(如上图)
好比:android:configChanges="orientation|keyboard|keyboardHidden"
当Configuration改变后,ActivityManagerService将会发送"配置改变"的广播,会要求ActivityThread 从新启动当前focus的Activity.
这是默认状况,咱们不作任何处理,若是咱们android:configChanges来配置Activity信息,那么就能够避免对Activity销毁再从新建立,而是调用onConfigurationChanged方法。
经过查阅Android API能够得知android:onConfigurationChanged实际对应的是Activity里的onConfigurationChanged()方法。
在AndroidManifest.xml中添加上诉代码的含义是表示在改变屏幕方向、弹出软件盘和隐藏软键盘时,再也不去执行onCreate()方法,而是直接执行onConfigurationChanged()。
若是不申明此段代码,按照Activity的生命周期,都会去执行一次 onCreate()方法,而onCreate()方法一般会在显示以前作一些初始化工做。
因此若是改变屏幕方向这样的操做都去执行onCreate() 方法,就有可能形成重复的初始化,下降程序效率是必然的了,并且更有可能由于重复的初始化而致使数据的丢失。这是须要千万避免的。