部分網友會發現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
}
}