Android WebView app Example in Kotlin

With an Android WebView, you can show website in android application. Web-view is containers like scrollView, ListView etc in Android app development. You can add it using Android studio drag-drop or in XML code directly. Purpose of WebView is if you want a web application or just a web page in your app

In Android WebView class is an extension of Android’s View class that allows you to display web pages as a part of your activity layout or other resources layout.

Android WebView app Example in Kotlin android studio

Let’s build an Android webView application

In this example, we are using Kotlin language with WebView and showing Responsive website in mobile. Also, we will add “If web view have back history, then go to the web view back history”.

 

Simply Adding a WebView to Your Application

To add a WebView to your Application, simply include the <WebView> element in your resource layout file. For example, here’s a layout file in which the WebView match the screen, if you are suing LinearLayout or Relative Layout for ConstraintLayout you have to set with GUI builder (drag and drop).

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

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

private val url = "http://tutorial.eyehunts.com/"
webview.loadUrl(url)

Before this will work, however, your application must have access to the Internet. To get Internet access, request the INTERNET permission in your manifest file. For example:

<manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

 

Enabling JavaScript

JavaScript is disabled in a WebView by default. If your website is using JavaScript (Nowadays every side using) then you must have to enable JavaScript.

// Get the web view settings instance

val setting = webview.settings;

// Enable javascript in web view

setting.javaScriptEnabled = true

 

Navigating web page history

When you go inside webpage to webpage and then click Back button app will close. So you can override back button override fun onBackPressed() and Handle back press.

override fun onBackPressed() {
        if (webview.canGoBack()) {
            // If web view have back history, 
            // then go to the web view back history
            webview.goBack()
        } 
    }

 

More web view settings

You can handle more setting of web view like :

  • Enable javascript in web view
  • Enable and setup web view cache
  • Enable zooming in web view
  • Zoom web view text
  • Enable disable images in web view
  • safeBrowsingEnabled

Many more option google android doc

 

Complete code

Create an android project in the android studio (Follow this tutorial: Android First Program in Android Studio)

Add WebView in main_activity.xml, used ConstraintLayout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.eyehunt.webviewexample.MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Add fowling code in MainActiviyt.xml, the code in Kotlin, know more about basic fundamentals of kotlin 

package `in`.eyehunt.webviewexample

import android.graphics.Bitmap
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val url = "http://tutorial.eyehunts.com/"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the web view settings instance
        val settings = webview.settings;

        // Enable java script in web view
        settings.javaScriptEnabled = true

        // Enable and setup web view cache
        settings.setAppCacheEnabled(true)
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.setAppCachePath(cacheDir.path)


        // Enable zooming in web view
        settings.setSupportZoom(true)
        settings.builtInZoomControls = true
        settings.displayZoomControls = true


        // Zoom web view text
        //settings.textZoom = 125


        // Enable disable images in web view
        settings.blockNetworkImage = false
        // Whether the WebView should load image resources
        settings.loadsImagesAutomatically = true


        // More web view settings
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            settings.safeBrowsingEnabled = true  // api 26
        }
        //settings.pluginState = WebSettings.PluginState.ON
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings.mediaPlaybackRequiresUserGesture = false
        }

        // More optional settings, you can enable it by yourself
        settings.domStorageEnabled = true
        settings.setSupportMultipleWindows(true)
        settings.loadWithOverviewMode = true
        settings.allowContentAccess = true
        settings.setGeolocationEnabled(true)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.allowUniversalAccessFromFileURLs = true
        }

        settings.allowFileAccess = true

        // WebView settings
        webview.fitsSystemWindows = true

        /* if SDK version is greater of 19 then activate hardware acceleration
        otherwise activate software acceleration  */

        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null)

        webview.loadUrl(url)

        // Set web view client
        webview.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                // Page loading started
                // Do something
            }

            override fun onPageFinished(view: WebView, url: String) {
                // Page loading finished
                // Enable disable back forward button
            }
        }
    }

    override fun onBackPressed() {
        if (webview.canGoBack()) {
            // If web view have back history, then go to the web view back history
            webview.goBack()
        }
    }
}

Note: Don’t forget to add internet permission in AndroidManifest.xml

It will throw an error or not upload webpage in the app.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.eyehunt.webviewexample">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Output screenshot android web view app :

 

android web view example

 

Download Link and Source code Android WebView in Github

https://github.com/EyeHunts/WebViewexample

 

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in JAVA

Bonus: How to Display Web Pages in Android KitKat 4.4 – Java


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.