代码如下:
AndroidManifest.xml
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<activity
android:name=".Activity1"
android:label="@string/app_name"
android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Activity1.java
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged");
if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Log.d(TAG, "竖屏");
}
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
Log.d(TAG, "横屏");
}
}
旋转屏幕后,程序重新加载Activity,onConfigurationChanged
方法未被调用.
08-11 11:19:21.716 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onPause
08-11 11:19:21.716 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onStop
08-11 11:19:21.716 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onDestroy
08-11 11:19:21.736 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onCreate
08-11 11:19:21.746 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onStart
08-11 11:19:21.746 23435-23435/com.zm.kingsoft.myapplication D/Activity1﹕ onResume
解决方法:
AndroidManifest.xml
中设置android:configChanges="orientation|screenSize“
原因解释:
自从Android 3.2(API 13),screen size
也开始跟着设备的横竖切换而改变。
所以,在AndroidManifest.xml
里设置的MiniSdkVersion
和 TargetSdkVersion
属性大于等于13的情况下,如果你想阻止程序在运行时重新加载Activity,除了设置"orientation"
,还必须设置"ScreenSize"
。