Reputation: 1422
I have two layouts in layout and layout-land folders. The problem is when the orientation change, it will call onCreate method. How to prevent onCreate method called?
This is what I've done. But it didn't work at all.
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
}
Upvotes: 1
Views: 2175
Reputation: 2562
You can use
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
or
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
to lock the orientation. Because as you mentioned, the onCreate is called everytime the screen rotates.
But you have to call it before the setContentView(R.layout.main) Could look like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main);
}
or android:screenOrientation="sensorPortrait"
like this in your AndroidManifest
<activity
android:name=".ActivitiesClasses.Login"
android:label="@string/app_name"
android:screenOrientation="sensorPortrait"
android:theme="@style/AppTheme.NoActionBar" />
Upvotes: 1
Reputation: 5011
When orientation is changed it needs to load new layout with new configuration. it needs to recreate it. So, there is no way to exit this recreation.
There are some way to avoid it :
onsaveinstancestate
. Where you can save your view state & in onCreate
you can get the savedInstance & repopulate it.Save Your Activity State
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);
}
Restore Your Activity State
@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)
. Then fragment will not destroyed while activity is destroyed.Refs :
Upvotes: 2
Reputation: 9121
Add this in manifest file for your Activity
android:configChanges="keyboardHidden|screenSize|orientation"
Upvotes: 1