0

我知道这个问题已经被问了很多次,因为我搜索了全部的答案,但是,可惜的是,我没有找到答案,主要是因为没有人似乎是使用基类Android类的碎片&,而不是他们都使用Sherlock片段类。onCreateOptionsMenu没有被调用内部片段

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

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

这是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也相同片段内

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

} 

我的基地主要FragmentActivity类没有onCreateOptionsMenu本身,但我不认为这会影响片段。

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

所以,如果任何人有任何想法可以解决这个问题,我真的很感激它!

非常感谢!

+1

调用'setHasOptionsMenu(真)'在'的onCreate(..)'的片段 –

+0

确保你的Activity调用super.onCreateOptionsMenu() –

回答

2

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); 
} 
+0

哇哦!其实!我完全按照你所说的完成了,它现在完美了!非常感谢!! :d –

相关问题