Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Action Bars with two fragments

I have a layout with two fragments and both fragments have their own action bars, each of which have their own action items and menus. When my app is in landscape mode and both fragments are displayed on the screen, it looks like the framework is choosing to display the action bar on the "right" (or the 2nd fragment), which means the fragment on the left (1st fragment) is missing its action items and menu options.

Everything works fine when the app is in portrait mode, so I'm not sure if I should be doing something to handle the fragments when they are both displayed. Thanks.

EDIT

In each of my fragments I'm using this code to add menu items to the Action Bar:

In fragment 1:

    @Override
    public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_menu_1, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

In fragment 2:

    @Override
    public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_menu_2, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

UPDATE:

Apparently using setRetainInstance(true) is what caused the menus not to refresh. I was using that because I have an AsyncTask that was throwing an exception if the device was rotated. So I fixed one issue, but broke another.

like image 695
Kris B Avatar asked Jan 17 '23 23:01

Kris B


1 Answers

I think you're thinking about this incorrectly. The action bar is not displayed as part of any fragment, but actually as part of the activity. If you declare in your fragments that you provide action items via setHasOptionsMenu(true), then all will be displayed as part of the action bar. You can then take the appropriate action by overriding onOptionsItemSelected(MenuItem item).

like image 198
Jason Robinson Avatar answered Jan 24 '23 23:01

Jason Robinson