How to generate ContextMenu Items Dynamically at run time?

390 Views Asked by At

I'm creating a Music player app and I want to display names of available playlists when user want to add any song to playlist, in contextMenu.

So the whole scenario is: When user long presses on any song, a contextMenu having one of the options named Add to playList is shown. When user clicks that menu item, Another contextMenu having options Create a new PlayList and names of playlist previously available (if any) is shown.

Snap shot:

enter image description here

Now the problem is, To show the names of previously stored playlists, I think I have to generate this menu Items dynamically at run time. My code of adding menu items is:

    @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    if(contextMenuFlag){

        menu.setHeaderTitle(songToDisplay);
        menu.add(Menu.NONE, PLAY_SONG, Menu.NONE, "Play");
        menu.add(Menu.NONE, ADD_TO_PLAY_LIST, Menu.NONE, "Add to Playlist");
    }
    else{
        contextMenuFlag = true;
        menu.setHeaderTitle("Add to Playlist");
        menu.add(Menu.NONE, CREATE_PLAYLIST, Menu.NONE, "-Create a new Playlist");
        menu.add(Menu.NONE, 10, Menu.NONE, "Old Playlists if exists");
    }
    //Toast.makeText(MainActivity.this,v+"",Toast.LENGTH_SHORT).show();
}

Here using loop, I think I can add menu items dynamically. But the problem is in handling click events on menu items. Code of this event handling is:

    @Override
public boolean onContextItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case PLAY_SONG: {
            songClick(MyView);
        }
        break;
        case ADD_TO_PLAY_LIST: {

            contextMenuFlag = false;
            songView.post(new Runnable() {

                @Override
                public void run() {
                    songView.showContextMenu();
                }
            });
        }
        break;
        case CREATE_PLAYLIST:{
            addToPlayList();
        }
        break;
    }
    return super.onContextItemSelected(item);
}

Here I'm using switch case for each menu Item ID. So my question is how to handle click events in switch case if I've added menu items at runtime?

Please suggest alternatives if any. Thank you.

0

There are 0 best solutions below