1

How can I add menu items to the menu of the DrawerLayout in Java and set onOptionsItemSelected to it. (I don't know how many items are needed; the user adds them)

I have an arraylist of custom objects that have a title that I want to display in the menu and when clicked on the item I want to change what is being displayed in the main Activity, by passing which one of the objects was clicked on.

I know that it is possible to add a menu item like this, but the problem is that I don't know how many there are going to be, so setting the onOptionsItemSelected to the right amount of items is what I am looking for

private static final int MENU_ITEM_ITEM1 = 1;
...
@Override
   public boolean onCreateOptionsMenu(Menu menu) {
   menu.add(Menu.NONE, MENU_ITEM_ITEM1, Menu.NONE, "Item name");
   return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
        case MENU_ITEM_ITEM1:
           return true;

        default:
           return false;
   }
}

Thanks for your help!

EDIT:

I see how how this might seem like a duplicate question, but the other questions and answers did not help. I am looking for a way to set onOptionsItemSelected to an unknown amount of items (the size of an ArrayList) and then display the selected Object in the main Activity Thanks

jonasxd360
  • 1,225
  • 4
  • 19
  • 35
  • 4
    Possible duplicate of [how we can add menu item dynamically](https://stackoverflow.com/questions/17311833/how-we-can-add-menu-item-dynamically) – ADM Nov 25 '17 at 18:16
  • I see how how this might seem like a duplicate question, but the other questions and answers did not help. I am looking for a way to set onOptionsItemSelected to an unknown amount of items (the size of an ArrayList) and then display the selected Object in the main Activity Thanks – jonasxd360 Nov 25 '17 at 18:30
  • I think for that you should should use PopUpWindow. Cause as you you said unknown amount of items . In this case PopUpWindow will be better option with an adapter. – ADM Nov 25 '17 at 19:20
  • thank you for your help, this seems like a good solution – jonasxd360 Dec 02 '17 at 18:47

0 Answers0