Pass parameters to WebView in Android

The html you want to display in WebView and pass a string to it. Create the file at app/src/main/assets/html/index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <style>
          #message {
            width: 100%;
            text-align: center;
            font-size: 24px;
          }
        </style>
    </head>
    <body>
        <p id="message">...</p>
        <script type="text/javascript">
                function loadMsg(msg) {
                    document.getElementById("message").innerHTML = msg;
                }
        </script>
    </body>
</html>

The WebView in a layout file for rendering html pages.

<WebView
  android:id="@+id/wv_html_content"
  android:layout_width="match_parent"
  android:layout_height="match_parent"></WebView>

The Android code to load a local html page and pass a string to it.

WebView wvContent = (WebView) findViewById(R.id.wv_html_content);
WebSettings webSettings = wvContent.getSettings();
webSettings.setJavaScriptEnabled(true);
wvContent.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished (WebView view, String url) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        view.evaluateJavascript("loadMsg('How are you today!')", null);
    } else {
        view.loadUrl("javascript:loadMsg('How are you today!')");
    }
}
});
wvContent.loadUrl("file:///android_asset/html/index.html");

Search within Codexpedia

Custom Search

Search the entire web

Custom Search