Derived Context MenuInfo

Figure 5-3. Activities, views, and context menus

There is one more notable wrinkle to the context menu. Whereas the onCreateOptionsMenu() method is automatically called for every activity, this is not the case with onCreateContextMenu(). A view in an activity does not have to own a context menu. You can have three views in your activity, for example, but perhaps you want to enable context menus for only one view and not the others. 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, which we'll discuss in the section "Registering a View for a Context Menu."

Now note the ContextMenuInfo class shown in Figure 5-3. An object of this type is passed to the onCreateContextMenu method. This is one way for the view to pass additional information to this method. For a view to do this, it needs to override the getContextViewInfo() method and return a derived class of ContextMenuInfo with additional methods to represent the additional information. You might want to look at the source code for android.view.View to fully understand this interaction.

Note Per the Android SDK documentation, context menus do not support shortcuts, icons, or submenus.

Now that you know the general structure of the context menus, let's look at some sample code that demonstrates each of 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.

0 0

Post a comment