sigmabeta sigmabeta - 1 month ago 13
Android Question

Action Bar Button won't respond to Touch events

I would like to have a

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

private Button mButton;

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

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

menu.getItem(0).setActionView(mButton);

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
getItem(1)
) set up the way a button normally works - with an
onClickListener
- and it works fine.

What am I missing?

Answer

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.

Comments