Working with Context Menus
Android supports the idea of context menus through an action called a long click.
context menu is represented as a ContextMenu class in the
Android menu architecture. a context menu is owned by a view, the method to populate context menus resides in the Activity class. This method is called activity.onCreateContextMenu(),
and its role resembles that of the activity.onCreateOptionsMenu() method.
If you want a particular view
to own a context menu, you must register that view with its activity specifically for the
purpose of owning a context menu. You do this through the
activity.registerForContextMenu(view) method,
the steps to implement a context menu:
1. Register a view for a context menu in an activity’s onCreate() method.
2. Populate the context menu using onCreateContextMenu(). You must
complete step 1 before this callback method is invoked by Android.
3. Respond to context-menu clicks.
A first step
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)this.findViewById(R.id.textViewId);
registerForContextMenu(this.getTextView());
}
B:Populating a Context Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("Sample Context Menu");
menu.add(200, 200, 200, "item1");
}
C:Responding to Context Menu Items
@Override
public boolean onContextItemSelected(MenuItem item)
{
if (item.itemId() = some-menu-item-id)
{
//handle this menu item
return true;
}
}