【发布时间】:2017-12-18 20:01:09
【问题描述】:
我正在尝试从屏幕捕获用户触摸事件(现在基本上我只关注按钮点击)。以下是我遵循的两种方法。
方法 1:在活动顶部使用覆盖屏幕。
为了捕捉触摸事件,我重写了 OnTouchListener 接口的 onTouch 方法。通过 MotionEvent 我得到 X,Y 坐标,但我不知道触摸发生在按钮上。并且总是触摸返回动作 ACTION_OUTSIDE。我被困在那里以识别按钮上发生的触摸。
方法 2: 直接处理活动上的触摸事件。
为了捕获触摸事件,我重写了 Activity 类的 dispatchTouchEvent 方法。每当屏幕上有触摸时,会捕获 1 次触摸 3 个事件(ACTION_DOWN、ACTION_MOVE、ACTION_UP)。我参考了这个链接 (How to tell if an X and Y coordinate are inside my button?) 并利用它的第三个答案来了解按钮上发生的触摸。我为共享的示例使用了 2 个视图。
以下是相同的代码。
Rect outRect = new Rect();
int[] location = new int[2];
1. private View myView = inflater.inflate(R.layout.xxact_copy_popupmenu, null); // empty screen
2. myView = getWindow().getDecorView().getRootView();
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d(TAG, "Dispatch-touch me");
if (event.isButtonPressed(MotionEvent.ACTION_BUTTON_PRESS)) {
Log.d(TAG, "****BUTTON PRESSED****");
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (inViewInBounds(myView, (int) event.getRawX(), (int) event.getRawY())) {
Log.e("dispatchTouchEvent", "you touched inside button");
} else {
Log.e("dispatchTouchEvent", "you touched outside button");
}
}
return super.dispatchTouchEvent(event);
}
private boolean inViewInBounds(View view, int x, int y) {
view.getDrawingRect(outRect);
view.getLocationOnScreen(location);
outRect.offset(location[0], location[1]);
return outRect.contains(x, y);
}
当在代码中使用第一个 myView 时,即使我们按下按钮(以及按钮外部),它也会返回我们说它没有按下按钮。如果使用第二个 myView 并按下屏幕上的任意位置(按钮上和按钮外),它会显示按下按钮。
所以我被困在这里如何进一步进行。请帮助我识别按钮上发生的触摸。
【问题讨论】:
标签: android