Automatically remove popup menu

I am inflating a popup menu in my application. I created a popmenu xml as shown below.

Song_popup xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/ToolBarStyle">

    <item
        android:id="@+id/add_queue"
        android:title="Add to queue" />
    <item
        android:id="@+id/play_next"
        android:title="Add to favourite" />
    <item
        android:id="@+id/add_download"
        android:title="Download" />


</menu>

      

Now I want to remove the item by checking the condition. How can i do this?

code

PopupMenu popup = new PopupMenu(activity, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.song_popup, popup.getMenu());
popup.show();

      

+3


source to share


3 answers


You can remove the menu item as shown below:

Menu m = popup.getMenu();
m.removeItem(m.findItem(R.id.add_queue));  //removes "Add to queue"

      

The implementation of the condition is entirely up to you.




and you can handle clicks of menu items:

popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        if(menuItem.getItemId() == R.id.play_next){
            Toast.makeText(YourActivity.this, "Play_next", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
});

      

+10


source


Unless I missed something, it should be as simple as this:



if (doNotShowAddQueue) {
    final Menu menu = popup.getMenu();
    menu.removeItem(R.id.add_queue);
}

      

+1


source


You can do it simply. the ex -

if (popup != null && yourcondition){
      MenuItem menuitem=    popup.getMenu().getItem(1);
      menuitem.setVisible(false);
    }

      

0


source







All Articles