我在布局和布局 - 土地文件夹中有两个布局。问题是当方向改变时,它会调用onCreate方法。如何防止onCreate方法调用?
这就是我所做的。但它根本不起作用。
AndroidManifest
<activity android:name=".MapsActivity"
android:configChanges="orientation|keyboardHidden">
MapsActivity.java
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
orientationChange = true;
//reload your ScrollBars by checking the newConfig
}
答案 0 :(得分:1)
在活动
的清单文件中添加此项android:configChanges="keyboardHidden|screenSize|orientation"
答案 1 :(得分:1)
更改方向时,需要使用新配置加载新布局。它需要重新创建它。所以,没有办法退出这种娱乐活动。
有一些方法可以避免它:
onsaveinstancestate
。您可以在哪里保存您的视图状态&amp;在onCreate
,你可以获得savedInstance&amp;重新填充它。保存您的活动状态
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
恢复您的活动状态
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
setRetainIntace(true)
。然后片段不会在活动被破坏时被破坏。参考:
答案 2 :(得分:0)
您可以使用
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
或强>
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
锁定方向。因为正如您所提到的,每次屏幕旋转时都会调用onCreate。
但你必须在setContentView(R.layout.main)之前调用它可能看起来像这样:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
}
或 android:screenOrientation="sensorPortrait"
在您的 AndroidManifest
中这样<activity
android:name=".ActivitiesClasses.Login"
android:label="@string/app_name"
android:screenOrientation="sensorPortrait"
android:theme="@style/AppTheme.NoActionBar" />