I have a similar scenario as shown on the sample of android website about fragments (link here) :
The action bar in my case is always shown, and for now I only have action items in it.
The next scenario is very weird:
Device has one pane for portrait, and 2 panes for landscape.
Both of my fragments create their own action bar items.
Switching from portrait to landscape show all of the action items (which is what I want)
Switching from landscape to portrait show all of the action items.
This doesn't make much sense as the right pane doesn't exist, yet for some reason its fragment seems to exist in the fragmentManager, and its onCreateOptionsMenu is called even though it's not shown at all.
I've tried to call invalidateOptionsMenu() on the activity that holds both fragments, but it didn't help
I've also added the next code for each of the fragments, and it works perfectly:
@Override
public void onStart() {
super.onStart();
setHasOptionsMenu(true);
}
@Override
public void onStop() {
super.onStop();
setHasOptionsMenu(false);
}
Why does it happen?
Is my solution of enabling/disabling the optionsMenu (thus enabling/disabling the action bar items creation by the fragments) a viable solution? Is there a better solution?
Is it even a good thing to make the fragments handle the action items in the first place?
I generally only have fragments handle action bar items in the single-pane case. Logically the visible fragment owns all the screen space at that point, and since there's limited screen real estate it makes sense to use the action bar. In the dual-pane case I tend to keep each fragment's UI within its own fragment and don't use the action bar. However, if it makes visual sense in your scenario I don't see any reason why you can't.
My understanding is that the set of fragments in existence before a configuration change is recreated after a configuration change. Android doesn't rely on the activity's layout file or anything like that. Whatever fragments you have created is considered to be state to be preserved across configuration changes. You might try manually removing the potentially unnecessary fragment when your activity is being torn down, and then count on Android to recreate it from the layout if it needs to exist after all. However this is educated musing and not tested.
That said I don't see anything wrong with your current solution.