Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide item from popupmenu

I created a popup menu. I need to hide a particular item from popup menu on condition, I tried this below code but it doesn't work and shows "unexpectedly your app has been stopped". I used findViewById and setEnabled(false).

Is there any other way to hide an item from popup menu? Please help with this.

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch(item.getItemId()){
        case R.id.addMessage_Action:
            AddMessage();
            break;
        case R.id.dropMenuAction:
            menuItemView = findViewById(R.id.dropMenuAction);
            PopupMenu popup = new PopupMenu(this, menuItemView);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.popupmenu_for_message_delete, popup.getMenu());
            popup.show();
            popup.setOnMenuItemClickListener(this);
            if(Global.lock == true)
                findViewById(R.id.lock_message).setEnabled(false);
            else
                findViewById(R.id.unlock_message).setEnabled(false);

            break;
        }
        return false;

    }
like image 485
Selvarathinam Vinoch Avatar asked Aug 23 '13 00:08

Selvarathinam Vinoch


2 Answers

You need to get the Menu Object from the PopupMenu before you get the item. So it'd be something like

Menu popupMenu = popup.getMenu();
if(Global.lock == true)
    popupMenu.findItem(R.id.lock_message).setEnabled(false);
else 
    popupMenu.findItem(R.id.unlock_message).setEnabled(false);

And I'd do this before you call popup.show()

like image 98
tim Avatar answered Nov 11 '22 19:11

tim


This answer may be helpful to someone,

I used below

popupMenu.getMenu().findItem(R.id.next).setVisible(true);

If you want to change the text of the menu, you can use below code,

popupMenu.getMenu().findItem(R.id.next).setTitle("After");
like image 42
Thirumalvalavan Avatar answered Nov 11 '22 19:11

Thirumalvalavan