在片段的Android选项菜单 [英] Android Options Menu in Fragment
问题描述
我想一个项目从一组片段添加到选项菜单。
I am trying to add an item to the options menu from a group of fragments.
我创建了一个新的 MenuFragment
类和扩展这个,因为我希望包含在菜单项的片段这里是code:
I have created a new MenuFragment
class and extended this for the fragments I wish to include the menu item in. Here is the code:
public class MenuFragment extends Fragment {
MenuItem fav;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
fav = menu.add("add");
fav.setIcon(R.drawable.btn_star_big_off);
}
}
由于某种原因, onCreateOptionsMenu
似乎没有运行。
任何帮助将是AP preciated。
Any help would be appreciated.
推荐答案
你有没有所谓的超级方法?
Have you called the super method?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
在code将日志语句,看是否该方法不会被调用,或者如果菜单不被修正你的code。
Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.
此外,还要确保您所呼叫 SetHasOptionsMenu
在的onCreate
来通知,它应该参与选项菜单操作的片段。
Also ensure you are calling SetHasOptionsMenu
in onCreate
to notify the fragment that it should participate in options menu handling.
这篇关于在片段的Android选项菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!