旋转屏幕后,片段的选项菜单没有消失。

4
我根据这篇教程实现了我的布局:http://android-developers.blogspot.hu/2011/02/android-30-fragments-api.html 区别在于:
  • 我有不同的片段要显示,基于左侧列表中的选择。
  • “详细信息片段”(出现在右侧)有不同的选项菜单。
我的问题是,如果我已经从左侧选择了某个选项,然后将手机旋转到纵向,最后一个选项菜单仍然存在并可见。
我认为问题来自于方向更改后重新创建了上一个活动的“详细信息”片段。 为测试它,我创建了这两个方法:
@Override
public void onStart() {
    super.onStart();
    setHasOptionsMenu(true);
}

@Override
public void onStop() {
    super.onStop();
    setHasOptionsMenu(false);
}

我这样展示正确的片段:

case R.id.prefs_medicines:
        if (mDualPane) {


            // Check what fragment is shown, replace if needed.
            View prefsFrame = getActivity().findViewById(R.id.preferences);
            if (prefsFrame != null) {
                // Make new fragment to show this selection.
                MedicineListF prefF = new MedicineListF();

                // Execute a transaction, replacing any existing
                // fragment with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.preferences, prefF);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), MedicinePrefsActivity.class);
            startActivity(intent);
        }
        break;

在我的“详情”片段中,当我调试它时,onStart方法在旋转后被调用。
问题如下图所示:
1. 横屏模式下正常 横屏模式 http://img834.imageshack.us/img834/8918/error1d.png 2. 竖屏模式下optionsmenu不需要 竖屏模式 http://img860.imageshack.us/img860/8636/error2r.png 如何在竖屏模式下去掉optionsmenu?
1个回答

5

我曾经遇到过同样的问题,解决方法是仅在 savedInstanceState 为 null 时在片段中设置 setHasOptionsMenu(true)。如果 onCreate 获取了一个 bundle,则表示该片段正在恢复横向方向的肖像,因此不要显示菜单。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null) {
        setHasOptionsMenu(true);
    }
}       

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接