Android WebView in Kotlin for absolute beginners

What is WebView

Using WebView on Android without using Cordova

We will select the ‘Basic Activity’. Then click on the ‘Next’ button. The next screen asks you what you want to name the app and the Package name.

Pick a name for your application, package, and choose ‘Kotlin’ for the language. Then click on the ‘Finish’ button, and Android Studio will create the template for the application.

Adding the WebView

In the palette on the upper left hand side, select ‘Widgets’, then click and drag the ‘WebView’ widget into the center of the view. Once you have dropped it into place, we will need to fix the constraints. We can do this by clicking on the ‘Infer Constraints’ button at the top of the view window. It looks like a magic wand. Once this has been done, the semi-circles at the top, bottom, left and right of the view will turn blue.

In the ‘Attributes of the view we are going to rename the id from ‘webView’ to ‘myWebView’.

Changing the activity

Now we can add our code for loading the a website into the WebView. Add the following code to the ‘onCreate’ method after the setSupportActionBar. You should put your app url within myWebView.loadUrl(“ www.mywebApp.com”).

For demonstration purposes I will use www.google.com

You will also need to add the android.webkit.WebView to the imports at the top of the activity as well as android.webkit.WebViewClient and android.webkit.WebResourceRequest.

In order to load an external website into the WebView, you will have to add a permission to the AndroidManifest.xml file for INTERNET access. After the </application> tag, add the INTERNET permission.

Tapping on a link in the WebView

JavaScript is by default turned off in WebView widgets. Hence web pages containing JavaScript references won’t work properly. To enable JavaScript the following snippet needs to be called on the webView instance:

Now you should be able to run your app and have it use the new WebView widget. Lets see what we get below:

et Voila!

Computer science graduate 2021. 1 year technology placement in investment banking. Full stack:ReactJS, JavaScript, NodeJS,Flask,SQL, AWS Crypto enthusiast