On an app that I'm working on, I need a context menu to show up if a user performs a longClick on a tab, which would allow them to close the tab. I can't seem to find a way to add a listener to a tab though. I either need each tab to have its own listener or the listener needs to be able to tell which tab had the longClick performed on it, as it won't always be the active tab.
Any ideas?
I appreciate that an answer has been accepted but if you want to utilise the built-in ContextMenu
capabilities rather than set onLongClickListeners
on the TabWidget
itself, you can do this as follows...
Example, my current TabActivity
adds tabs in a for
loop and to register each for context menu I do the following.
for (int tabNumber = 1; tabNumber < 8; tabNumber++) {
...
spec = tabHost.newTabSpec(tag).setIndicator(indicator).setContent(intent);
tabHost.addTab(spec);
View v = tabWidget.getChildAt(tabNumber - 1);
registerForContextMenu(v);
...
}
Then in my Activity
I simply override onCreateContextMenu(...)
and onContextItemSelected (MenuItem item)
@Override
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) {
...
// The parameter v is the actual tab view and not the TabWidget
// this makes it easy to get the indicator text or its tag in order
// to easily identify which tab was long-clicked and build the menu
...
}
@Override
public boolean onContextItemSelected (MenuItem item) {
...
// Process selected item here
...
}
There's no need to set an OnLongClickListener
on any views explicitly as that is done by the call to registerForContextMenu(...)
. Also, the ContextMenu
creation and selection handling is all handled for you by the ContextMenu
methods exposed by Activity
.
Unless you need to handle all of this stuff yourself (for a custom context menu layout for example) it seems easier to just use what's buit-in to Activity
.