android - 方向改变后, fragment 的选项菜单不会消失

标签 android screen-orientation

我根据本教程实现了我的布局:http://android-developers.blogspot.hu/2011/02/android-30-fragments-api.html

区别是:

  • 根据左边的选择,我有不同的 fragment 要显示 列表
  • “细节 fragment ”(右边的 fragment )有不同的选项菜单

我的问题是,如果我已经从左侧选择了一些东西,然后将手机旋转到纵向,最后一个选项菜单仍然存在并且可见。

我认为问题出在方向更改后重新创建了最后一个 Activity 的“详细信息” fragment 。为了测试它,我创建了这两种方法:

@Override
public void onStart() {
    super.onStart();
    setHasOptionsMenu(true);
}

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

我正在展示正确的 fragment ,如下所示:

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;

在我的一个“细节” fragment 中。当我调试它时,在轮换之后调用了onstart。

图片中的问题:

1: 横屏没问题 Landscape mode http://img834.imageshack.us/img834/8918/error1d.png

2:纵向:不需要选项菜单 Portrait mode http://img860.imageshack.us/img860/8636/error2r.png

如何去掉纵向模式下的选项菜单?

最佳答案

我遇到了同样的问题,仅当 savedInstanceState 为 null 时,通过在 fragment 中设置 setHasOptionsMenu(true) 解决了这个问题。如果 onCreate 获得一个包,则 fragment 将在方向更改为纵向的情况下恢复,因此不显示菜单。

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

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

关于android - 方向改变后, fragment 的选项菜单不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11297210/

相关文章:

java - 为整个应用程序禁用横向模式

java - 更改屏幕方向时重置操作

android - WebView 未自动加载

android - 在 LinearLayout 上实现 OnTouchListener - Android 开发

android - 为 recyclerview 和 textview 翻译动画不流畅

screen-orientation - 为 Android 平板电脑编程时屏幕尺寸是否重要?

java - 致命异常 NoClassDefFoundError

android - 在 Android Switch 组件上定义自定义样式(主题)

android - appWidget 定位代码

android - 通过方向更改保存下载的位图