Trần Văn Hòa
Trần Văn Hòa

Reputation: 173

Click ImageView in WebView android

In my Webview I have many tag img(ImageView) and I want get event when click tag img in webview to show position of it in many image. How i do?

Upvotes: 0

Views: 2032

Answers (3)

Swapnil Meshram
Swapnil Meshram

Reputation: 128

First of all you need to enable javascript. like this,

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

then bind your javascript code with android code,

public class WebAppInterface {
Context mContext;

/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
    mContext = c;
   }

/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
   }
}

then add javascriptInterface Method with webview, It will call your android method from any javascript method,

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

After that in your webview page just add onclick method on each tag img, and call javascript method from onclick event,

<img src="YOUR IMAGE SOURCE" id="your img positon OR anything" onClick="showAndroidToast(this.id)" />

<script type="text/javascript">
function showAndroidToast(toast) {
    Android.showToast(toast);
}
</script>

for more reference please refer Android Webview

Upvotes: 1

Sirisha Jayanti
Sirisha Jayanti

Reputation: 99

What I understand is that you need to find out when an image in the webview is clicked.

If so, you can use this : http://developer.android.com/reference/android/webkit/WebView.html#getHitTestResult()

and this :

http://developer.android.com/reference/android/webkit/WebView.HitTestResult.html

use it in your click listener and it should work!

Upvotes: 1

Rami
Rami

Reputation: 7929

Use a Javascript Interface to bind Javascript code (from html) to Android code.

eg:

JavascriptInterface:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

HTML (JS):

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

Add the JavaScriptInterface to your WebView:

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

This is an example from the official documentation.

And this is another tutorial.

Upvotes: 0

Related Questions