我正在依次替换两个碎片,这两个碎片都有不同的选项菜单。当我替换第二个碎片时,它也显示了第一个碎片的菜单。在两个碎片中都设置了setHasOptionsMenu(true);。
我只想显示特定的碎片中创建的选项菜单,并避免其他碎片的选项。请帮忙,谢谢。
我只想显示特定的碎片中创建的选项菜单,并避免其他碎片的选项。请帮忙,谢谢。
这就是您的活动将会如何表现
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
//your menu item
return true;
}
return super.onOptionsItemSelected(item); // important line
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true); //imp line
return inflater.inflate(R.layout.fragment_following, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_1:
// do stuff
return true;
case R.id.action_2:
// do more stuff
return true;
}
return false;
}
在替换片段(或提交片段事务)后,您必须声明选项菜单已更改,可以通过调用invalidateOptionsMenu()
来实现。下一次需要显示时,将调用onCreateOptionsMenu(Menu)方法。
注意:如果您正在使用AppCompat支持库,则需要调用supportInvalidOptionsMenu。