Handling Action Bars with two fragments

僤鯓⒐⒋嵵緔 提交于 2020-01-13 11:20:37

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/10096625/handling-action-bars-with-two-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!