Reputation: 629
I use this code to check if a user touched inside a webview
webview.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_UP)
{
//action
}
return false;
}
});
but I will need to do action only if user clicked (touched ) a link only ,not if the the user touch some pictures or do a scrool in webview. I need to reinit some variables when new webpage is loaded ,or when a user clicks on a link , but not when he click random on screen or he do scrool. i can not use
public void onPageStarted(WebView view, String url, Bitmap favicon)
or
public boolean shouldOverrideUrlLoading(WebView view, String url)
cause this are called multiple times while a page is loaded and I only need to do action first time only 1 time , when user click on a link (or button or something that make webview to load a new page)
Does anybody knwo how to do this?
Thank you in advance
Upvotes: 0
Views: 2503
Reputation: 19253
first step - enable JavaScript:
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
second step - create interface between Java and Javascript:
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();
}
}
register your interface:
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
and put this JS in your html page:
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
example for html:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
if pages which you are showing are not your you might download them as plain text, then insert JS and load html with myWebView.loadDataWithBaseURL. this way you have full control of which user is clicking and what to do with it
to be honest I don't understand why you cannot do this with shouldOverrideUrlLoading(WebView view, String url)
by checking what is arriving in url
String and setting 'consumed' flag or smth like this
also: whole code is stolen from HERE
Upvotes: 2