- February 14, 2016
When you rotate/change the orientation of your Android application the Activity will be destroyed and recreated. What this means is that any variables, fragments will be destroyed when the user changes the orientation of their device (say going from portrait to landscape). Your users will hate you. For example, If they are filling out a form and by accident the orientation changes all fields entered will be lost.
How can we avoid this bad experience? There are a few ways.
Within the OnCreate of the Activity you can force the orientation to one or the other. A user can rotate the device however the user interface does not change orientation.
Using an attribute on the class will lock the orientation. The following ignores the orientation and the screen size changes. This is easy however the difficulty is that your application will not be responsive to size/orientation changes. Your application will respond to different screen sizes or orientation. This too can be less than optimum.
In the following example I have an application with three fragments. The first fragment with tag “Fragment1” gets set when the application loads. I will use this tag as the test to see if the activity has started at least one time. Within the OnCreate method I check to see if the Activity has run by checking SupportFragmentManager.FindFragmentByTag(“Fragment1”).
I am going through this backwards but this is the method that I am using to replace the current fragment with a new one. Notice however that I am adding it with a specified tag so that we can recover it later
And finally I will show the method that responds to a menu selection which calls the ReplaceFragment method
So finally, why are we using the transaction manager to replace fragments instead of showing and hiding them? If we load up all fragments upon start up and show/hide they all are residing in memory which can be problematic if the fragments are large or you have many of them in your application. Using the replace approach optimizes memory to only work with active fragments. While a fragment is not in the current layout it is ‘paused’ and the memory footprint is much less.
Reference: http://developer.android.com/guide/components/fragments.html