0

I have two screens and two xml-files for one activity. In my onCreate method I call the fist one and handle some user input. After that I am changing my layout with

setContentView(R.layout.activity_quiz2);

and everything is fine and works as intended but when I run the application and turn my device after I switched the layouts. It will just switch back to the first layout and stay on that layout (every button and all works as well).

How can I prevent my screen from changing back my layouts when I turn my device?

Brian
  • 14,610
  • 7
  • 35
  • 43
Tim
  • 1
  • 3
  • When you rotate a device, the entire activity is rebuilt from scratch, meaning any changes you've made are discarded and onCreate is run again. If you want to keep changes, you've got to look at onSaveInstanceState and using a Bundle to register where you were in the app. – Joseph Roque May 19 '15 at 15:30
  • yeah you have to save your state to the bundle. Check this [link](http://stackoverflow.com/questions/151777/saving-activity-state-in-android) – Kasun Dissanayake May 19 '15 at 15:32
  • you need to handle one flag if you are changing layout then store flag value in sharedpreference and then check for that flag from sharedpreference if its true than set second xml as your layout or else set first as you content of activiy. – Jitesh Dalsaniya May 19 '15 at 16:04

1 Answers1

0

It's switching back to the first layout because when you rotate the screen the whole Activity is recreated. You have couple of options to deal with this:

  1. Add android:configChanges="orientation" to your <activity element in the AndroidManifest.xml file. This way you're telling the system you want to deal with the rotation yourself (and if needed you can perform some actions in onConfigurationChanged() method).

  2. Use Fragments to display the two "states" you have (I'm assuming those are quiz1 and quiz2). This way you won't need to do multiple setContentView() in your activity.

The second option is the one to go for, as that's basically what Fragments are all about. Not to mention you can do very nice transitions between them (fade-in-out animations, etc) and your UX will be much better than when swapping the setContentView().

Vesko
  • 3,750
  • 2
  • 23
  • 29