How do I detect keypress and which key user pressed on SubMenu? [the one on the actionbar where user press and a long list would drop down]
SubMenu subMenu1 = menu.addSubMenu("Option");
subMenu1.add("Comments");
subMenu1.add("More screens");
subMenu1.add("Copy Website URL");
subMenu1.add("Go to Website");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setIcon(R.drawable.icon_share);
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
I suppose you mean “which item a user selects” in the menu, and not “which key a user pressed”. You can provide the action in the
onOptionsItemSelected()method that you already have. But before, you have to…Either change the way that you programmatically add items to your subMenu a little, following this solution: https://stackoverflow.com/a/9080046/1140682
Or define your menu and submenu in an XML file and use the
MenuInflaterto add the items to yourActivity.Finally, just use the
itemIdparameter from theadd()method (first solution) or theandroid:idfrom the XML (second solution) to decide on an action in theswitchstatement ofonOptionsItemSelected().