Populating a Context Menu

Once a view like the TextView in this example is registered for context menus, Android will call the onCreateContextMenu() method with this view as the argument. This is where you can populate the context menu items for that context menu. The onCreateContextMenu() callback method provides three arguments to work with.

The first argument is a preconstructed ContextMenu object, the second is the view (such as the TextView) that generated the callback, and the third is the ContextMenuInfo class that we covered briefly while discussing Figure 5-3. For a lot of simple cases, you can just ignore the ContextMenuInfo object. However, some views might pass extra information through this object. In those cases, you will need to cast the ContextMenuInfo class to a subclass and then use the additional methods to retrieve the additional information.

Some examples of classes derived from ContextMenuInfo include AdapterContextMenuInfo and ExpandableContextMenuInfo. Views that are tied to database cursors in Android use the AdapterContextMenuInfo class to pass the row ID within that view for which the context menu is being displayed. In a sense, you can use this class to further clarify the object underneath the mouse click, even within a given view.

Listing 5-16 demonstrates the onCreateContextMenu() method.

Listing 5-16. The onCreateContextMenu() Method ^Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

menu.setHeaderTitle("Sample Context Menu"); menu.add(200, 200, 200, "iteml");

0 0

Post a comment