[英]How do I hide the OptionMenu in a toolbar from a fragment?
I inflate the option menu in the HomeActivity
. 我在
HomeActivity
选项菜单。 But i need the option menu to show in some fragments
, and hide in others. 但是我需要选项菜单来显示某些
fragments
,而隐藏在其他fragments
中。
I tried with setHasOptionsMenu(false);
我尝试了
setHasOptionsMenu(false);
line in onCreate()
fragment method. onCreate()
片段方法中的行。
This is the optionmenu
button declaration in HomeActivity
这是
optionmenu
按钮声明HomeActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//initialize button
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
//action when i press it
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.toolbar_acquista:
Toast.makeText(this, "Acquisto", Toast.LENGTH_SHORT)
.show();
break;
}
return true;
}
I'm trying to have this in a fragment
the option menu clickable
and visible, in others unclickable
and invisible. 我正在尝试使此
fragment
在选项菜单中clickable
和可见,而在其他菜单中则不可unclickable
和不可见。
first Clear Menu
like 首先
Clear Menu
例如
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
}
and then TRUE as setHasOptionsMenu(true);
然后TRUE作为
setHasOptionsMenu(true);
in onCreate()
of fragment method 在片段方法的
onCreate()
中
don't inflate menu in home activity instead inflate menu inside the fragments 不要在家庭活动中膨胀菜单,而是在片段内部膨胀菜单
like this 像这样
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sample, menu);
super.onCreateOptionsMenu(menu,inflater);
}
this way menuitems inflated in the fragments only visible when the fragment is visible 这样,只有当片段可见时,菜单项才会在片段中膨胀
First of all Override Create Method in Fragment and write setHasOptionsMenu(true) 首先在Fragment中覆盖Create方法并编写setHasOptionsMenu(true)
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Then after override OnPrepareOptionMenu method in Fragment and Write code which i place inside it. 然后在Fragment中重写OnPrepareOptionMenu方法并编写放置在其中的代码。 I hide my Search Menu only.
我只隐藏搜索菜单。 Similarly You can hide all menu item or selective item as per your choice.
同样,您可以根据自己的选择隐藏所有菜单项或选择项。
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.menu_search);
if(item!=null)
item.setVisible(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.