【问题标题】:onCreateOptionsMenu isn't being called inside Fragments片段内部未调用 onCreateOptionsMenu
【发布时间】:2013-10-19 13:59:51
【问题描述】:

我知道自从我到处寻找答案以来,这个问题已经被问过很多次了,但遗憾的是,我没有找到答案,主要是因为似乎没有人使用基本的 Android 类对于 Fragments,它们都使用 Sherlock Fragment 类。

首先,我没有使用任何 Sherlock Activity 或 Android 支持库。我只是使用默认的 Fragment 类:

import android.app.Fragment
import android.view.Menu
import.android.view.MenuItem
import.android.view.View
//& so on...

这是我 Fragment 中的 onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment1, null);
    setHasOptionsMenu(true);
    return root;
}

& 这是 onCreateOptionsMenu 也在同一个 Fragment 中

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getActivity().getMenuInflater();
    menu.clear();
    inflater.inflate(R.menu.fragment1_menu, menu);

//A lot of other code here

return super.getActivity().onCreateOptionsMenu(menu);

}

我的基础 Main FragmentActivity 类本身没有 onCreateOptionsMenu,但我认为这不会影响 Fragments。

另外,我似乎无法覆盖 onCreateOptionsMenu,我得到的错误是; onCreateOptionsMenu 必须覆盖或实现超类型方法。

如果有人有任何可以解决这个问题的想法,我将不胜感激!

非常感谢!

【问题讨论】:

  • 在片段中的onCreate(..) 中调用setHasOptionsMenu(true)
  • 确保你的Activity调用了super.onCreateOptionsMenu()

标签: java android eclipse android-fragments android-fragmentactivity


【解决方案1】:

onCreateOptionsMenu() 的方法签名在 Fragment 中与 Activity 中的不同,如 the documentation 中所示。

将您的实现更改为:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
   inflater.inflate(R.menu.fragment1_menu, menu);

   //A lot of other code here

   super.onCreateOptionsMenu(menu, inflater);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多