使用getSupportFragment

时间:2017-04-17 03:58:57

标签: android optionmenu

早安男士,

我试图在某些片段上隐藏选项菜单。例如,我只想在促销页面上显示选项菜单

enter image description here

我在promotion.java中添加了代码

public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    inflater.inflate(R.menu.toolbar_menu, menu);

    super.onCreateOptionsMenu(menu,inflater);
}

然后我想隐藏在其他片段上。

当我启动应用时,第一个片段就像enter image description here

但是当我点击促销页面并点击返回菜单页面时,操作栏将会是这样的

enter image description here

我使用getSupportFragment来调用菜单项,这个问题只发生在使用getSupportFragment调用的片段上。

case R.id.menu:
                 getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MenuFragment()).addToBackStack(null).commit();

2 个答案:

答案 0 :(得分:3)

如果您想从Fragment控制选项菜单,则必须在setHasOptionsMenu(true)的{​​{1}}中致电onCreate()

Fragment

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } 清除menu

onCreateOptionsMenu()

或者:您可以通过覆盖@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); } show/hide特定菜单item

onPrepareOptionsMenu

答案 1 :(得分:1)

在片段onCreate中添加setHasOptionsMenu(true)

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

然后

@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);//your id instead of action_search
item.setVisible(false);
}
相关问题