Ad

I Need To Hide/show A Particular Item From Popup Menu On Given Condition

- 1 answer

I tried this solution, but it doesn't work as I expected.
Here is my code, and this is what i have tried.

PopupMenu popup = new PopupMenu(TableActivity.this, view);
              popup.setOnMenuItemClickListener(TableActivity.this);
              menu = popup.getMenu();
              popup.inflate(R.menu.popup_shift);
              popup.show();
              popup.setOnMenuItemClickListener(this);

    @Override
     public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_merge:
                    if(tableDbList.get(positionShift).getMergeTableId()== 0) {     
                      //this is the condition to show/hide popup menuitem  
                         popup.getMenu().findItem(R.id.menu_merge).setVisible(false);
                    }else {   
                    checkPinCode.checkPinCodemethod(TableActivity.this,   "mergeCancel");
                    }
         }
     return true;
    }
Ad

Answer

You are trying to change visibility on MenuItem click . It will work but popupMenu will dismiss just after click . So it does not make any sense. If your requirement is to show items on some condition you should set visibility before show(). Below is a simple example .

  private void showPopup() {
    final PopupMenu popup = new PopupMenu(MainActivity.this, view);
    popup.getMenuInflater().inflate(R.menu.popup_shift, popup.getMenu());
    if(someCondition){
        popup.getMenu().findItem(R.id.menu_merge).setVisible(false);
    }
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
    });
    popup.show();
}
Ad
source: stackoverflow.com
Ad