我有一个片段,需要建立自己的操作栏:
public class CalendarFragment extends Fragment {
public CalendarFragment() {
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().supportInvalidateOptionsMenu();
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.calendar_menu1, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText("Calendar Fragment");
return textView;
}
}
问题是它没有创建一个包含来自calendar_menu1的项目的新菜单,只是将其中的项目添加到旧菜单中,就好像invalidateOptionsMenu不起作用(我也尝试了getActivity()。invalidateOptionsMenu())
答案 0 :(得分:5)
你必须调用onCreate():
setHasOptionsMenu(true);
答案 1 :(得分:3)
这是正常的,查看MenuInflater的javadoc,“项目和子菜单将添加到此菜单”:
public void inflate (int menuRes, Menu menu)
Inflate a menu hierarchy from the specified XML resource. Throws InflateException if there is an error.
Parameters
menuRes Resource ID for an XML layout resource to load (e.g., R.menu.main_activity)
menu The Menu to inflate into. The items and submenus will be added to this Menu.
您是否尝试过调用menu.clear()
来扩充片段菜单?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.calendar_menu1, menu);
}