Adding onclick to a submenu?

I have an onclick function for my menu, but I can’t understand what the identifier is for my submenu so that I can specify the submenu what to do when the user clicks on it. I created my submenu programmatically using the code below. Therefore, if someone can explain to me how I know what the identifier means for each element of the submenu, I would be very grateful to him.

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences"); submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 5 Packets"); submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 10 Packets"); submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 20 Packets"); inflater.inflate(R.menu.mainmenu, submenu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.viewKML: viewKML(); return true; default: return super.onOptionsItemSelected(item); } } 
+6
source share
1 answer

When you add

 submenu.add(0, Menu.FIRST, Menu.NONE, "Get Last 5 Packets"); 

Layout of parameters for add () method Method for adding Android menu

 public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title) 

itemId Unique identifier for the item. Use NONE if you do not need a unique identifier.

It is the identifier of your menu item. It must be unique. As you say, 15,20,21. This identifier will act like android:id="@+id/15" . Will be used when you are going to check which item is clicked.

eg

 @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_activity_menu, menu); SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences"); submenu.add(0, 10, Menu.NONE, "Get Last 5 Packets"); submenu.add(0, 15, Menu.NONE, "Get Last 10 Packets"); submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets"); inflater.inflate(R.menu.main_activity_menu, submenu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case 10: Toast.makeText(LoginPageActivity.this, "Now "+item.getItemId(), Toast.LENGTH_SHORT).show(); return true; case 15: Toast.makeText(LoginPageActivity.this, "Now = "+item.getItemId(), Toast.LENGTH_SHORT).show(); return true; case 20: Toast.makeText(LoginPageActivity.this, "Now == "+item.getItemId(), Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } 
+10
source

Source: https://habr.com/ru/post/907311/


All Articles