sigmabeta sigmabeta - 1 year ago 73
Android Question

Action Bar Button won't respond to Touch events

I would like to have a

in my
that does something when you touch it, and something else when you release it.

private Button mButton;

public boolean onPrepareOptionsMenu(Menu menu) {
mButton = (Button) getLayoutInflater().inflate(R.layout.action_button, null);

mButton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent e) {
Log.d(TAG, "This line never executes...");
return false;


return super.onPrepareOptionsMenu(menu);

As written above, nothing in onTouch ever happens when I touch the Button. I have another button in the same menu (I get it with
) set up the way a button normally works - with an
- and it works fine.

What am I missing?

Answer Source

The ActionMenuPrestener is an internal class that controls the menus that appear in the ActionBar. If a MenuItem has submenu, it will attach a View.OnTouchListener that allows the user to drag their finger forward to open the submenu. If the MenuItem doesn't have a submenu, is sets the View.OnTouchListener to null.

In other words, you can't attach a View.OnTouchListener to a MenuItem because the framework will remove it. You best bet is to create a custom View for your ActionBar, then attach a View.OnTouchListener to that.

If you'd like to view the source for the ActionMenuPrestener, you can do so here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download