Some controls or regions in the user interface allow for additional actions to be performed. However, due to limited screen space, these actions need to be hidden until the user requests them.
this.RegisterForContextMenu(someView);
OnCreateContextMenu()
method:public override void OnCreateContextMenu( IContextMenu menu, View view, IContextMenuContextMenuInfo menuInfo) { base.OnCreateContextMenu(menu, view, menuInfo); MenuInflater.Inflate(Resource.Menu.Main_Options, menu); }
OnContextItemSelected()
method:public override bool OnContextItemSelected(IMenuItem item) {
if (item.ItemId == Resource.Id.action_refresh) {
// do something here...
return true;
}
return base.OnContextItemSelected(item);
}
We can provide a context menu for any view, but they are most often used for items in a list, grid, or other view collection. One way to show a contextual menu is to use a floating or pop-up menu, and it is the recommended way for apps supporting versions of Android below version 3.0.
When the user long-taps on a view that has been registered for a context menu, the activity or fragment attempts to display a menu that is created or inflated in the OnCreateContextMenu()
method.
After the user selects an item from the contextual menu, the OnContextItemSelected()
method on the activity or fragment is invoked. In this method, we initiate the desired operation that was selected. We can identify the selected item using the ItemId
property.
Using the IContextMenu
instance that is passed into the OnCreateContextMenu()
method, we can change or remove the header of the popup menu. The header could be a combination of an icon and/or text or a separate custom view:
menu.SetHeaderTitle("My Context Menu Heading");