Android menu callbacks for taps and long presses
Android apps can expose commands through an action bar, a popup, or a menu opened by long-pressing content. Understanding bubbling and contextual menus begins with identifying which component owns each command: a tapped toolbar action and a long-pressed list row follow different callback paths even when both end at the same activity.
Each path needs its own creation, preparation, and selection logic. The examples below use Kotlin with XML resources, but the same responsibilities apply in Java and other Android UI toolkits. The key rule is to consume a selection only after the handler knows which object it affects.
Following the route of a menu selection
Android does not route every kind of menu in exactly the same way. For an options item, a fragment can receive onOptionsItemSelected before the hosting activity. Returning false leaves that item unhandled, allowing the activity or a default action to process it; this fallback is the practical meaning of bubbling in a menu hierarchy.
A contextual command instead reaches onContextItemSelected, together with MenuInfo describing the long-pressed view. Keep the paths explicit: options commands act on screen or app state, while contextual commands usually act on a particular row, file, image, or selected text.
Creating an options menu with a safe fallback
Create a menu resource with stable item IDs. These IDs connect the XML definition to the callback and should not change casually, because deep links and automated tests may rely on them.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_share"
android:title="@string/action_share"
android:showAsAction="ifRoom" />
</menu>
Inflate that resource in the activity or fragment and handle each known ID in a when expression. The final branch delegates unknown items to the superclass, preserving normal Android behaviour.
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_editor, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_share -> {
shareCurrentText()
true
}
else -> super.onOptionsItemSelected(item)
}
}
Returning true tells Android that the callback consumed the command. Returning false or calling the superclass is appropriate when another owner should receive it; it also prevents one tap from triggering both a fragment handler and an activity handler.
Turning a long press into a contextual menu
Register the view that should react to a long press, then inflate a separate resource in onCreateContextMenu. This example assumes the registered view is an AdapterView, such as a ListView.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/context_copy" android:title="@string/copy" />
<item android:id="@+id/context_reply" android:title="@string/reply" />
</menu>
registerForContextMenu(messageList)
override fun onCreateContextMenu(
menu: Menu,
view: View,
menuInfo: ContextMenuInfo?
) {
super.onCreateContextMenu(menu, view, menuInfo)
menuInflater.inflate(R.menu.menu_message_context, menu)
}
Use onContextItemSelected to read the target and perform the action. The following handler obtains the selected row position, handles Copy, and leaves Reply available for another implementation.
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as? AdapterView.AdapterContextMenuInfo
?: return false
return when (item.itemId) {
R.id.context_copy -> {
copyMessage(info.position)
true
}
else -> super.onContextItemSelected(item)
}
}
The two paths suit different interaction models:
| Behaviour | Options or bubbling action | Contextual action |
|---|---|---|
| Trigger | Tap in the action bar, toolbar, or menu | Long-press a view or row |
| Main callback | onOptionsItemSelected |
onContextItemSelected |
| Target | Current screen or app state | Object identified by MenuInfo |
| Common use | Save, share, search, settings | Copy, edit, delete, reply |
| Fallback | Return false to let a parent handle it |
Return false if no target is valid |
Handling ownership and preparation callbacks
Always resolve the selected object before acting. AdapterContextMenuInfo supplies an adapter position for a ListView, but that position can become stale if the data changes. For a RecyclerView, pass a stable row ID through custom ContextMenuInfo and look the item up again when it is selected.
Preparation callbacks are also where dynamic menus belong. onPrepareOptionsMenu can change visibility, enablement, titles, and checked states, while onPrepareContextMenu can tailor actions to the selected object. Call invalidateOptionsMenu after changing relevant state. Always return a definite result from selection handlers: true for handled commands and false only when another handler should continue.
Keeping menus clear for Australian users
Use Australian English in visible labels, such as “favourite” and “organisation”, rather than importing US spelling. Australians commonly shorten “afternoon” to “arvo”, so a scheduling action may use that familiar word, but it should also show a clear clock time. Perth is two hours behind Sydney, and Melbourne sits on Australian Eastern Time, so a menu that changes a time should never rely on informal wording alone.
Australia’s app market is driven largely by Google Play, and commuters on Sydney and Melbourne trains often depend on mobile data with variable coverage. Contextual commands should therefore act immediately on cached content and avoid starting a slow network request before the menu closes. Short labels, generous touch targets, and clear consequences also help when a user opens a menu one-handed while travelling.
Testing menu behavior on real devices
For a live conversation screen, the WebSocket chat example shows how messages can arrive asynchronously. A contextual action must still target the row that was long-pressed, even if another message arrives before the user chooses Copy or Reply. Stable IDs and target lookup prevent that race from changing the selected object.
Test long presses, taps outside the menu, keyboard navigation, large fonts, dark mode, and TalkBack on several Android versions and screen sizes. Confirm that options icons remain reachable, contextual rows scroll correctly, and every command produces one visible result. On newer Android code, MenuProvider and PopupMenu can supply similar callbacks, but IDs and ownership rules should remain consistent. A menu that selects the right item, consumes each callback once, and works with assistive technology is ready for production.