2

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

Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
  • You need save and restore value when change screen mode. [See here][1] [1]: http://stackoverflow.com/questions/151777/how-do-i-save-an-android-applications-state – Volodymyr Jul 16 '12 at 13:17
  • Thank you, but I just can't save ALL the things I created in a bundle... I have several objects and stuff. Everything has to be re-created every time someone rotates the screen?? – Sebastian Breit Jul 16 '12 at 13:20
  • you can put those stuff in your application object, and access them from your activity – marcinj Jul 16 '12 at 13:30

2 Answers2

4

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.
Jin35
  • 8,602
  • 3
  • 32
  • 52
0

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.

Volodymyr
  • 1,037
  • 1
  • 11
  • 27