How To Capture MenuItem Events Of Context Menu From Within A View & Not An Activity In Android

This came as odd to me. From within an Activity class, you can create a context menu through the onCreateContextMenu() and capture those events and process code in the onOptionsItemSelected() method.

Since I was extending an existing View class, it does have its own onCreateContextMenu() but with only one parameter needed with is ContextMenu.

Here is the problem then. There is no onOptionsItemSelected() for the View class but only for Activity.

How then can events of the context menu items be captured? The answer is none that you can just override some method directly.

What I did though, was traversing each MenuItem in the Menu and adding an OnMenuItemClickListener to each one. That did the trick.

Here is a sample code.

By the way, make sure you register your view that will show the context menu by doing this:

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *