Reputation: 6159
I know this question was already asked, but mine is a little different:
I have 2 different layout files for my game; one for portrait mode and one for landscape. When I rotate the screen, the onCreate method restarts my game (creates all the elements again). I don´t want this to happen, so I wrote this line in the manifest:
android:configChanges="orientation"
It works, onCreate is not called, but the new layout is not being showed properly!
I tried to put the following code in my Activity, but it just keeps doing weird things:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.gameview);
}
how can I fix this? thanx guys
Upvotes: 2
Views: 1927
Reputation: 1047
You should use onRetainNonConfigurationInstance() for save state and for restore state getLastNonConfigurationInstance() for any objects. Or hard-code set android:screenOrientation="portrait/landscape" in manifest.
Upvotes: 0
Reputation: 8612
First of all understand how orientation changing in android works:
By default activity restarts on orientation changed event (and goes throw onCreate
).
If you write android:configChanges="orientation"
in manifest - it means it will not be recreated, but just remeasure and redraw view tree.
Comments about your code:
setContentView
should called just once per activity lifecycle.General way to handle this situation is:
onSaveInstanceState
onCreate
method restore game state if it is supplied (savedInstanceState
param is not null).Upvotes: 4