Hiding context menu items

219 Views Asked by At

There is a context menu in my application, but I want to hide its items when a particular condition is specified. What should I do ?

This is onCreateContextMenu code

   @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        menu.setHeaderTitle("Select the Action");

        menu.add(0,0,getAdapterPosition(), Common.EDIT_POST);
        menu.add(0,1,getAdapterPosition(),Common.DELETE_POST);

    }
1

There are 1 best solutions below

0
Neerajlal K On

Create a global variable. Change its state when your condition is met. Do not add the menu items you want to hide to menu.

// Declare as global inside Activity
private customCondition = true;

...
// Check if your condition has been met and change the variable state
if(isConditionMet()) {
   customCondition = false;
} else {
   customCondition = true;
}
...

Now inside onCreateContextMenu,

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    menu.setHeaderTitle("Select the Action");
    menu.add(0, 0, getAdapterPosition(), Common.EDIT_POST);

    if(!customCondition) {
        // Hide the delete post menuitem
        menu.add(0, 1, getAdapterPosition(),Common.DELETE_POST);
    }

}