I’m writing an Android application. I have two important XML files – main.xml, and new.xml. Here is my Java Activity source code:
// package declarations, imports, etc
public class MainActivity extends Activity {
@Override
public void onCreate(savedInstanceState) {
super.onCreate(savedInstancestate);
setContentView(R.layout.main);
}
// as you can see, the content of the initial layout is found in main.xml
// I want to change the layout so it has the content of new.xml (when I press a button)
public void ButtonAction(View view) {
setContentView(R.layout.new);
}
}
So it goes like this: in my main.xml file, there is a button. As dictated in the main.xml file, when I press that button, it calls the method ButtonAction. When the button is pressed and ButtonAction is called, I want to change the content of the layout to be the contents of new.xml.
The above code works, but only kind of – it’s not permanent. When I rotate my device, it appears to refresh the activity with the contents of main.xml. So I can get it to do what I want, but when I rotate the device and view it in a Landscape layout instead of the typical Portrait layout, it reverts.
How do I fix this?
Use onSaveInstanceState() to save the state of your activity and use onRestoreInstanceState() to retrieve the state your activity.
onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().
onRestoreInstanceState() is called only when recreating activity after it was killed by the OS.
Use the put methods to store values in onSaveInstanceState():
Here is a tutorial
http://www.androidcompetencycenter.com/tag/onrestoreinstancestate/