模拟鼠标单击

时间:2017-01-24 12:51:13

标签: android webview

我有点奇怪且罕见的任务:我想在WebView上模拟鼠标点击。

如果我的理解正确,我应该创建MotionEvent实例并将其传递给dispatchGenericMotionEvent方法。

我试过这个,它不起作用:

      float x = 100;
      float y = 100;
      long eventTime = SystemClock.uptimeMillis();
      long downTime = eventTime;

      // Press button
      MotionEvent motionEvent = getMotionEvent(x, y, MotionEvent.ACTION_HOVER_EXIT, eventTime, downTime, MotionEvent.BUTTON_PRIMARY);
      webView.dispatchGenericMotionEvent(motionEvent);

      eventTime += 100;
      downTime += 100;

      // Release button
      MotionEvent motionEvent1 = getMotionEvent(x, y, MotionEvent.ACTION_HOVER_ENTER, eventTime, downTime, 0);
      webView.dispatchGenericMotionEvent(motionEvent1);


   /**
    * Create MotionEvent instance
    */
   private MotionEvent getMotionEvent(float x, float y, int action, long eventTime,
                                      long downTime, int buttonState) {

      MotionEvent.PointerCoords pointerCoords = new MotionEvent.PointerCoords();
      pointerCoords.x = x;
      pointerCoords.y = y;
      MotionEvent.PointerCoords[] pointerCoordsArr = {pointerCoords};

      MotionEvent.PointerProperties pointerProperties = new MotionEvent.PointerProperties();
      pointerProperties.toolType = MotionEvent.TOOL_TYPE_MOUSE;
      pointerProperties.id = 0;
      MotionEvent.PointerProperties[] pointerPropertiesArr = {pointerProperties};

      int deviceId = 1;
      int pointerCount = 1;
      int metaState = 0;
      float xPrecision = 0;
      float yPrecision = 0;
      int edgeFlags = 0;
      int flags = 0;

      return MotionEvent.obtain(downTime, eventTime, action, pointerCount, pointerPropertiesArr,
              pointerCoordsArr, metaState, buttonState, xPrecision, yPrecision, deviceId,
              edgeFlags, InputDevice.SOURCE_MOUSE, flags);

   }

同时,WebView能够处理鼠标移动仿真:

  long eventTime = SystemClock.uptimeMillis();
  long downTime = eventTime;

  // go to 100, 100
  MotionEvent motionEvent = getMotionEvent(100, 100, MotionEvent.ACTION_HOVER_MOVE, eventTime, downTime, 0);
  webView.dispatchGenericMotionEvent(motionEvent);

  eventTime += 100;
  downTime += 100;

  // go to 101, 101
  MotionEvent motionEvent1 = getMotionEvent(101, 101, MotionEvent.ACTION_HOVER_MOVE, eventTime, downTime, 0);
  webView.dispatchGenericMotionEvent(motionEvent1);

为什么点击模拟无效?我做错了什么?

0 个答案:

没有答案