Android:使用webview的MotionEvent.obtain不起作用

时间:2013-12-18 14:34:12

标签: android webview ontouchevent motionevent

我对Android中的MotionEvent有疑问。我想发送一个“点击”到Webview,因为有一个iframe,我必须单击iframe中的图像/按钮。所以我不能你js,因为我无法控制iframe的内容。

我的代码:

private void simulateDoubleTapEvent(int action)
{
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis() + 100;
    float x = 35.407104f;
    float y = 378.52066f;
    // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
    int metaState = 0;
    MotionEvent me = MotionEvent.obtain(
        downTime, 
        eventTime, 
        action, 
        x, 
        y, 
        metaState
    );
    dispatchTouchEvent(me);
}

在onCreate:

webview2.setOnTouchListener(new OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
              int action = event.getAction();
               float x = event.getX();
               float y = event.getY();
                         event.getMetaState();
               Log.v("ON_TOUCH", "Action = " + action + " View:" + v.toString());
               Log.v("ON_TOUCH", "X = " + x + "Y = " + y);


           return false;
           }
   });
   webview2.setWebViewClient(new WebViewClient() {
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) 
    { view.loadUrl(url); return true; }
    public void onPageFinished(WebView view, String url) {
        Log.w("webview2","Load");

        simulateDoubleTapEvent(0);
                simulateDoubleTapEvent(1);
    }
   });

webView加载网址,但代码没有点击它。如果我点击webView,会触发onTouch事件。

你能帮帮我吗?

德国最好的问候。

1 个答案:

答案 0 :(得分:1)

将webview作为参数传递给simulateDoubleTapEvent()方法并将其用于调度。

private void simulateDoubleTapEvent(WebView view, int action)
{
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis() + 100;
    float x = 35.407104f;
    float y = 378.52066f;
    // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
    int metaState = 0;
    MotionEvent me = MotionEvent.obtain(
        downTime, 
        eventTime, 
        action, 
        x, 
        y, 
        metaState
    );
    view.dispatchTouchEvent(me);
}