如何为工具栏弹出(溢出)菜单设置OnTouchListener

时间:2015-04-11 12:35:07

标签: java android reflection android-5.0-lollipop

如果它是图片按钮(app:showAsAction="always"),我可以这样做:

findViewById(R.id.action_settings).setOnTouchListener(listener)

但如果它在溢出菜单(app:showAsAction="never")中,findViewById将返回null。什么是最简单,最便携的解决方案? (而不是很多反思)

P.S。我希望获得MotionEvent OnTouchListener中传递的触摸位置,因此我绝对不想知道如何使用onOptionItemsSelectedOnClickListener等等。

1 个答案:

答案 0 :(得分:0)

在我的演示应用程序中,我能够使用以下内容触发触摸事件:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = false;
    int id = item.getItemId();
    if (id == R.id.action_settings) {

        //Returning false here allows the touch event to bubble up.
        result = false;
    } else {
        result = super.onOptionsItemSelected(item);
    }
    return result;
}


@Override
public boolean dispatchGenericMotionEvent(MotionEvent ev) {
    Log.d(TAG, "dispatchGenericMotionEvent");
    // do some other stuff
    return super.dispatchGenericMotionEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.d(TAG, "dispatchTouchEvent");
    // do stuff here....
    return super.dispatchTouchEvent(ev);
}
相关问题