Reputation: 5
I inflate the option menu in the HomeActivity
. But i need the option menu to show in some fragments
, and hide in others.
I tried with setHasOptionsMenu(false);
line in onCreate()
fragment method.
This is the optionmenu
button declaration in 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.
Upvotes: 0
Views: 138
Reputation: 1496
First of all Override Create Method in Fragment and write 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. 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);
}
Upvotes: 0
Reputation: 492
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
Upvotes: 0
Reputation: 3100
first Clear Menu
like
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
}
and then TRUE as setHasOptionsMenu(true);
in onCreate()
of fragment method
Upvotes: 1