WebView is a component that allows you to display web pages as part of your Android app layout. It is an extension of the View class and does not have any features of a fully developed web browser, such as navigation controls or an address bar. You can use WebView to show online documents, such as user agreements or guides, or to load web pages that are tailored for Android devices.

WebView is very flexible and powerful, as it supports various web standards, such as HTML, CSS, JavaScript, and more. You can also bind JavaScript code to Android code, enabling communication between your web page and your app. For example, you can call a JavaScript function from your Android code, or vice versa.

How to use WebView in your Android app

There are two ways to add a WebView to your app: either by including the <WebView> element in your activity layout XML file, or by creating a WebView object programmatically in your activity's onCreate() method.

To add a WebView in your layout XML file, use the following code:

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

To load a web page in the WebView, use the loadUrl() method. For example:

val myWebView: WebView = findViewById(R.id.webview)
myWebView.loadUrl("[<http://www.example.com>](<http://www.example.com/>)")

To add a WebView in your onCreate() method, use the following code:

val myWebView = WebView(activityContext)
setContentView(myWebView)

Then load the web page with:

myWebView.loadUrl("[<http://www.example.com>](<http://www.example.com/>)")

You can also load HTML content from a string using the loadData() or loadDataWithBaseURL() methods. For example:

// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
val unencodedHtml = "<html><body>'%23' is the percent code for ‘#‘ </body></html>"
val encodedHtml = Base64.encodeToString(unencodedHtml.toByteArray(), Base64.NO_PADDING)
myWebView.loadData(encodedHtml, "text/html", "base64")

You can also use these methods to load inline HTML:

val htmlString = "data:text/html,<html><p>Hello :)</p></html>"
myWebView.loadUrl(htmlString)

Loading Local Files with WebView

webView.loadUrl("file:///android_asset/test.html", null)

JavaScript Interface For Communication

fun javaInterface(){
        class JsObject(){
            @JavascriptInterface
            fun logger(res: String){
                Log.v("JsObjectResult", res)
            }
        }
        myWebView.addJavascriptInterface(JsObject(), "JsObject")

        myWebView.webViewClient = object : WebViewClient(){
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                myWebView.evaluateJavascript("JsObject.logger(document.domain)", null)
            }
        }
        myWebView.settings.javaScriptEnabled = true

        myWebView.loadUrl("<https://ifconfig.io/>")

    }