Hide item from popupmenu

核能气质少年 提交于 2019-12-29 07:22:26

问题


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;

    }

回答1:


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()




回答2:


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");


来源:https://stackoverflow.com/questions/18392916/hide-item-from-popupmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!