方向改变后,片段的选项菜单不会消失

Ven*_*dii 4 android screen-orientation

我基于本教程实现了我的布局: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);
}
Run Code Online (Sandbox Code Playgroud)

而且我正在显示正确的片段:

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;
Run Code Online (Sandbox Code Playgroud)

在我的一个"细节"片段中.当我调试它时,在旋转后调用onstart.

图片中的问题:

1:在风景中它是好的 风景模式http://img834.imageshack.us/img834/8918/error1d.png

2:纵向:选项菜单不需要 肖像模式http://img860.imageshack.us/img860/8636/error2r.png

如何在纵向模式下摆脱选项菜单?

sid*_*ler 5

我遇到了同样的问题,只有当savedInstanceState为null时才通过在片段中设置setHasOptionsMenu(true)来解决它.如果onCreate获得一个包,则片段将在方向更改为纵向时恢复,因此不显示菜单.

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

    if(savedInstanceState == null) {
        setHasOptionsMenu(true);
    }
}       
Run Code Online (Sandbox Code Playgroud)