Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove popup menu item programmatically

I'm inflating a popup menu in my application. I've created a popmenu xml like 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 a item by checking a 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();
like image 882
CraZyDroiD Avatar asked May 25 '15 09:05

CraZyDroiD


3 Answers

You can remove a menu item as below:

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

Implementation of condition is totally up to you.


and this is how you can handle menu item clicks:

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;
    }
});
like image 196
waqaslam Avatar answered Oct 16 '22 16:10

waqaslam


You can do it simpily. ex-

if (popup != null && yourcondition){
      MenuItem menuitem=    popup.getMenu().getItem(1);
      menuitem.setVisible(false);
    }
like image 36
Chandra Sharma Avatar answered Oct 16 '22 15:10

Chandra Sharma


Unless I’m missing something, it should be as simple as e.g.:

if (doNotShowAddQueue) {
    final Menu menu = popup.getMenu();
    menu.removeItem(R.id.add_queue);
}
like image 1
Tadej Avatar answered Oct 16 '22 16:10

Tadej