Sebastian Breit
Sebastian Breit

Reputation: 6159

Activity restarts my game on screen rotation (Android)

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

Answers (2)

Volodymyr
Volodymyr

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

Jin35
Jin35

Reputation: 8612

First of all understand how orientation changing in android works:

  1. By default activity restarts on orientation changed event (and goes throw onCreate).

  2. 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:

  • If you have different layout for different orientations - you have to recreate activity on orientation changed.
  • Method setContentView should called just once per activity lifecycle.

General way to handle this situation is:

  1. Save game state in method onSaveInstanceState
  2. In onCreate method restore game state if it is supplied (savedInstanceState param is not null).
  3. Remove listening of configuration changing from manifest.

Upvotes: 4

Related Questions