Can unregisterForContextMenu completely unregister

2019-09-15 02:29发布

问题:

I have a ListView, which can either have a context menu, or not. I am using registerForContextMenu and unregisterForContextMenu respectively and have no problems with the registration itself or anything related to the context menu showing up/working.

When a view is registered for a context menu, when the user clicks it, its background changes gradually from orange through yellow and then to white. This does not happen when a view has never been registered for a context menu (it stays the same color). However, when I use unregisterForContextMenu to unregister the view in question, this effect is still active and may confuse the user - he/she will expect a context menu because of the effect. This shows that unregisterForContextMenu does not completely reverse the effect of registerForContextMenu.

My question is: Is there a way to completely unregister a View from getting a context menu?

If someone has a clearer idea of how (un)registerForContextMenu works internally, please share your thoughts.

Edit: I just saw that this does not apply to HTC's sense interface, as there the 'whitening' effect is not implemented. So the question applies only to the default Android interface.

回答1:

Turned out to be very simple. registerForContextMenu (View v) is simply calling v.setOnCreateContextMenuListener (this), referring to the calling Activity as the OnCreateContextMenuListener. The problem is that in the View class, the setOnCreateContextMenuListener is checking if the view is long-clickable, and if it isn't, it sets it to be. However, the method unregisterForContextMenu (View v) only calls v.setOnCreateContextMenuListener (null). But the setOnCreateContextMenuListener doesn't check whether the passed OnCreateContextMenuListener is null or not, thereby always leaving the view in question long-clickable.

The solution was to just call v.setLongClickable (false) manually.