I using menu drawer which has more Fragment
s. In some Fragment
s I have menu item REFRESH but in some fragments I want hide this menu item (I don\'t
please try this
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
}
and put this on your fragmen's onCreate()
setHasOptionsMenu(true);
Or solve it in the same Fragment which created the menu, if you host the Actionbar on Activity level. This way you don't have to add it on every other Fragment where you don't want to show it:
public override void OnDestroy()
{
base.OnDestroy();
HasOptionsMenu = false;
}
Add these functions to your Fragment
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.delete);
item.setVisible(false);
}
in Kotlin
override fun onPrepareOptionsMenu(menu: Menu) {
val item: MenuItem = menu.findItem(R.id.action_search)
item.isVisible = false
}
in onCreate() of your fragment setHasOptionsMenu(true)
Firstly in your Activity
that has the toolbar, create a method that sets up the overflow menu
for you:
public void setUpOptionMenu(Toolbar toolbar){
this.setSupportActionBar(toolbar);
}
In your fragments onCreateView()
method, get the reference of your current activity and call your activities setUpOptionMenu()
method:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
...
public void ((YourActivityName)this.getActivity()).setUpOptionMenu(null);
...
...
}
Cheers!!!
In the Fragment
where you don't want to show any menu options, you need setHasOptionsMenu(false);
in the onCreate()
, like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
However, the menu that is being shown that you would like to hide (REFRESH), belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment
level (and not show an Activity
options menu), my suggestion is to delete the menu code from the Activity
and implement it in your Fragment
.
Activity
s and Fragment
s can each have their own separate menus. See this link.