如何在webview的ontouchListener中获取<img/>标记的位置

时间:2013-02-08 13:07:34

标签: android webview touch image

我创建了一个具有滚动列表器和触摸Listner的自定义webview。我正在加载HTML代码,为此我使用了javascript,使用 for 循环创建img代码。

String htnlString = "<!DOCTYPE html><html><body style = \"text-align:center\"><script type=\"text/javascript\">for(a=1;a<=10;a++)document.write('<img style=\"border-style:dotted;border-width:10px;border-color:black;\"src=\"http://shiaislamicbooks.com/books_snaps/EN183/'+a+'.jpg\" alt=\"Page Not Found\"/>');</script></body></html>";

wv.loadDataWithBaseURL(null, htnlString, "text/html", "UTF-8", null);

现在我想获得webview的img标签onTouchListner的位置。 webview中是否有任何方法可以返回<img>标记的位置。

整个代码

import android.content.Context;
   import android.util.AttributeSet;
   import android.util.Log;
   import android.view.MotionEvent;
   import android.webkit.WebView;

   public class scorllableWebview extends WebView {
    private OnScrollChangedCallback mOnScrollChangedCallback;

public scorllableWebview(final Context context) {
    super(context);
}

public scorllableWebview(final Context context, final AttributeSet attrs) {
    super(context, attrs);
}

public scorllableWebview(final Context context, final AttributeSet attrs,
        final int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onScrollChanged(final int l, final int t, final int oldl,
        final int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    if (mOnScrollChangedCallback != null)
        mOnScrollChangedCallback.onScroll(l, t);
}

public OnScrollChangedCallback getOnScrollChangedCallback() {
    return mOnScrollChangedCallback;
}

public void setOnScrollChangedCallback(
        final OnScrollChangedCallback onScrollChangedCallback) {
    mOnScrollChangedCallback = onScrollChangedCallback;
}

/**
 * Impliment in the activity/fragment/view that you want to listen to the
 * webview
 */
public static interface OnScrollChangedCallback {
    public void onScroll(int l, int t);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.d("onTouchEvent", event.getAction() + "");

    // I want to get the position of <img> tag here.
   // what is the method which return the <img> tag position

    return super.onTouchEvent(event);
}
 }

提前致谢。

1 个答案:

答案 0 :(得分:0)

这取决于你获取触摸坐标的意思。

如果你的意思是在android坐标中,这是一个可能的解决方案:

  • 对于webview的onTouchListener,存储坐标并返回false,以便在websiew的内容中正常处理。

  • 在触摸webview中的img标签的javascript中,使用方法addJavascriptInterface调用android的函数(更多信息here),告诉它img标签被触摸。

  • 在此函数中,您可以获取之前保存的坐标。

如果你的意思是html坐标,你可以跳过第一步,然后简单地将它们传递给android框架。

相关问题