I want to refresh the option menu each time it is called,
I have a functionality in which when the user clicks the option(add/remove favourite) in option menu, it checks whether it is favourite or not and do the functionality,
Problem : Once it creates the menu , it does not refresh the onCreateOptionMenu on 2nd time user presses the option button. I want to refresh the optionMenu each time it is pressed. Here is my code for this
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (is_favorite.equals("1")) {
menu.add(1, 22 ,0,"Remove from Favourites").setIcon(R.drawable.favorites_unselected);
}
else{
menu.add(1, 11 ,0,"Add to Favourites").setIcon(R.drawable.favorites_selected);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu (Menu menu)
{
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case 11:
//addtofavouritestask
is_favorite = "1";
return true;
case 22:
//removeFromFavouritestask
is_favorite = "0";
return true;
default:
return super.onOptionsItemSelected(item);
}
}
According to the doc,
onCreateOptionMenu (Menu menu)is called only once time, so it does not refresh your menu. You must call the methodonPrepareOptionsMenu(Menu)to refresh it (” To update the menu every time it is displayed, seeonPrepareOptionsMenu(Menu)“).So this should work :