Reputation: 31
In a Webview, I am loading a local index.html file and adding HTML content using javaScript to Webview from remote. I want to perfrom some tasks like showing tooltip, alert box extra when users click on element contained by Webview. P.S It sounds like it has pretty straight forward solution. But I am able to do so ! Thanks!
Upvotes: 0
Views: 2166
Reputation: 11
shouldOverrideUrlLoading
ex.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url!= && url.endWith("your_url.html")) {
//your tootip, alertIDialog, etc.
// return true to report that we have intercepted the event
return true;
}
return super.shouldOverrideUrlLoading(view, url);
https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView, android.webkit.WebResourceRequest)
Upvotes: 1
Reputation: 2839
Adding a WebView to Your Application
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
In JAVA load URL
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
Add INTERNET Permission
<manifest ... >
<uses-permission android:name="android.permission.INTERNET" />
...
Enable javascript
in webview
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
Make Interface
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();
}
}
You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "android");
In your HTML
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
Hope this helped you
Source https://developer.android.com/guide/webapps/webview.html#AddingWebView
Upvotes: 1