In my fragment, I only want to show my Menu/MenuItems in my toolbar in landscape mode. When I change orientations, I am noticing that onCreateOptionsMenu and onPrepareOptionsMenu is not being called.
In other words, my landscape layout with my menu items only works when I start in landscape mode, but not when I try to change to landscape mode (crashes when changing from portrait to landscape).
public class MyFragment extends Fragment
{
private int orientation;
@Override
public void onCreate(Bundle savedInstanceState)
{
orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu)
{
initializeLandscapeMenuViews(menu);
super.onPrepareOptionsMenu(menu);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
if (orientation == Configuration.ORIENTATION_PORTRAIT)
initializePortraitMenuViews(view);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_layout, container, false);
}
// other code not shown
}
The crash occurs when I try to access the views that I initialize in initializeLandscapeMenuViews() because onPrepareOptionsMenu() is never called.
I checked the order of the calls using the debugger:
Starting in landscape mode
onCreateonViewCreatedonCreateOptionsMenuonPrepareOptionsMenu
then, orientation change to portrait
onCreateonViewCreated
then, orientation change back to landscape
onCreateonViewCreated
onCreateOptionsMenu and onPrepareOptionsMenu are not called
What am I missing? (Any help is appreciated).
Basically i am not seeing any problem with your approach. nevertheless, have you tried calling invalidateOptionsMenu()? It suppose to tell the OS you want to redraw your menus by calling onCreateOptionsMenu().