0

I'm working on an App with 3 fragments. When the App is launched I want one of the fragments to be loaded by default, and I achieve this by making a fragment transaction in the Activity OnCreate() method, however this method is also called when the screen is rotated and as a result the start fragment is loaded every time the user rotates the phone. How can I avoid this so the fragment transaction is only done if the app is launched but not if it's rotated.

Disabling rotation is not an option as I want it to be available in both landscape and portrait.

Essah
  • 899
  • 2
  • 8
  • 20
  • By checking whether the fragment is already there via the fragment manager: http://stackoverflow.com/questions/9294603/get-currently-displayed-fragment also requires that the fragment is retained otherwise it's deliberately not there and you have to make a new one. – zapl Nov 28 '15 at 16:21
  • @zapl I think this is a poor suggestion, since it requires retained fragments, which breaks the life cycle management benefits. The standard way is to check savedInstanceState and only add the Fragment the first time. This is in all of Google's code and is standard on Android. People should not be retaining fragments unless absolutely necessary, which is almost never. – rharter Nov 28 '15 at 16:32
  • 1
    @rharter Sure, you need to know what you're doing and why but why do they bother to make retaining fragments possible if you're not supposed to use that? And this is google too http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject - When you rely on the activities saved instance state you break the causal chain so checking with the fragment manager is IMO better when the question is "do I need to set the fragment". Whether you enable retained fragments is a different question. – zapl Nov 28 '15 at 16:44
  • While I agree that it can be useful and has its uses, its a powerful feature that often leads to other problems. In this case, the question is how to initialize and Activity with a Fragment, and the standard way, that I would argue covers 90% of cases, is to check the bundle and add the initial Fragment if it is null. Not that checking the Fragment manager is wrong, but checking the bundle is a simpler, standard mechanism. I just want to be careful, at this level, of suggesting retained instances, since that can be dangerous. – rharter Nov 28 '15 at 16:58
  • 1
    @rharter You win. I was forgetting that fragments are recreated after configuration change. – zapl Nov 28 '15 at 18:01

1 Answers1

2

The canonical way to do this is to only add the Fragment with the transaction if savedInstanceState == null. After rotation, or when the activity is recreated, the savedInstanceState will be a valid bundle.

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
            .add(R.id.container, myFragment)
            .commit();
}
rharter
  • 2,495
  • 18
  • 34