I use an xml to for my ContextMenu, which is like :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Ordermenu" android:title="Order">
<menu android:id="@+id/OrderBySubMenu">
<item android:id="@+id/OrderByASC" android:title="Order ASC" />
<item android:id="@+id/OrderByDESC" android:title="Order DESC" />
<item android:id="@+id/Cancel" android:title="Cancel" />
</menu>
</item>
<item android:id="@+id/ActionAmenu" android:title="Action A"/>
</menu>
I use following code to display the menu, in my onCreateContextMenu
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.my menu, menu);
I manage option click with following code :
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Displaymenu:
//do stuff
return true;
case R.id.OrderByASC:
//do stuff
return true;
case R.id.OrderByDESC:
//do stuff
return true;
default :
return(super.onOptionsItemSelected(item));
}
Starting the Context Menu it display Two options:
- Order
- Action A
Clicking on Order show a submenu :
- Order ASC
- Order DESC
- Cancel
Now, If the user click on cancel (or click on the hardware back button), no action is specified, so it call super.onOptionsItemSelected(item) which go back to my main activity.
How can I manage to go back to the main menu in such case? i.e. diplay the initial :
- Order
- Action A
Finally, it worked only by adding :
in public boolean onContextItemSelected(MenuItem item)
selected_view_id is stored by
in onCreateContextMenu
Hope it will help others.