【问题标题】:In android Is there any way to identify touch happened on a button or checking buttons available in the screen在android中是否有任何方法可以识别按钮上发生的触摸或检查屏幕上可用的按钮
【发布时间】: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


    【解决方案1】:

    我不确定您要做什么,但您可以通过以下方式监听按钮上的触摸事件:

    myButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
     });
    

    【讨论】:

    • @Shruthi I'm trying to capture the events from SDK not directly from the app- 我不太明白这一点。您能否更详细地解释一下您要实际实现的目标?我认为您误解了捕获视图的触摸事件的概念,因此试图将简单的事情复杂化。
    • 每当用户在整个屏幕上单击应用程序中的按钮时,我都会尝试捕获单击事件。我已经构建了应用程序 ABC 并且我有另一个项目 XYZ 转换为库。我的 ABC 项目中也导入了相同的内容。我在 XYZ 有自己的活动,并且 dispatchTouchEvent 在那里被覆盖。每当屏幕上有触摸时,我想通过这种方法了解触摸是否发生在按钮上。或者有没有其他方法可以捕获触摸事件或点击事件??
    • @Shruthi AFAIK 不可能。您还可以假设可能会出现的问题/安全问题。
    • 还有其他方法可以解决吗??谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2022-12-11
    • 1970-01-01
    相关资源
    最近更新 更多