onCreateOptionsMenu and onPrepareOptionsMenu not called on orientation change
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
onCreate
onViewCreated
onCreateOptionsMenu
onPrepareOptionsMenu
then, orientation change to portrait
onCreate
onViewCreated
then, orientation change back to landscape
onCreate
onViewCreated
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().
Edit: I thought TS was working with activities, but he's using fragments. Sorry.
If you're working with the activity: onCreateOptionsMenu
and onPrepareOptionsMenu
have a boolean return value. So, you nee to return a boolean (instead of void). In your current approach, you don't override the functions because of this. That's why it's seems like the functions are never called. For more info, see the API.
上一篇: jQuery Mobile的移动和桌面?