部分网友会发现Activity在切换到后台或布局从横屏LANDSCAPE切换到PORTRAIT,会重新切换Activity会触发一次onCreate方法,我们可以在androidmanifest.xml中的activit元素加入这个属性Android:configChanges="orientation|keyboardHidden" 即可,比如
<activity android:name=".android123" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name">
Java代码
/* 声明Display对象,以取得屏幕宽高 */
final Display defaultDisplay = getWindow().getWindowManager()
.getDefaultDisplay();
intScreenH = defaultDisplay.getHeight();
intScreenW = defaultDisplay.getWidth();
/* 如果为Landscape */
if (intScreenW > intScreenH)
{
/* Landscape => Portrait */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else
{
/* Portrait => Landscape */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
/* 声明Display对象,以取得屏幕宽高 */
final Display defaultDisplay = getWindow().getWindowManager()
.getDefaultDisplay();
intScreenH = defaultDisplay.getHeight();
intScreenW = defaultDisplay.getWidth();
/* 如果为Landscape */
if (intScreenW > intScreenH)
{
/* Landscape => Portrait */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else
{
/* Portrait => Landscape */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
同时在Activity的Java文件中重载onConfigurationChanged(Configuration newConfig)这个方法,这样就不会在布局切换或窗口切换时重载onCreate等方法。代码如下:
Java代码
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
//land
}
else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
//port
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
//land
}
else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
//port
}
}