Android WebView Kotlin

Android WebView allow you to display web content as part of your activity layout, WebView class is an extension of Android's View class , you can used it to Create web based application or just show/embed a web page in your app .

Lets See Example .

Project Detail
Project Name AndroidWebView
Package com.tutorialsbuzz.androidwebview
Min Sdk Version 22
Target Sdk Version 28
Compile Sdk Version 28
Theme Theme.AppCompat.Light.DarkActionBar


Android Manifest


 Add Internet Permission to manifest file .

file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.tutorialsbuzz.androidwebview">

    <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>

</manifest>


XML Layout 

  1. Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt) .
  2. Add Seekbar widget (used for adjusting textsize of the webview) .
  3. Add two Buttons (used for Back , Forward Navigation For Webview) .
  4. Add WebView to xml layout .
file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical">
    
    <include layout="@layout/navigator"/>

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

</LinearLayout>

WebView Loading WebContent


1. Loading From Asset.
webView.loadUrl("file:///android_asset/index.html")

2. Loading HTML Markup.
val htmlMarkup: String = "<html>\n" +
  "<body style=\"background-color: #FF9800; font-size: 16pt; color: #ffffff;\">\n" +
  "<div>\n" +
  "    welcome to \"www.tutorialsbuzz.com\"\n" +
  "    <br/>\n" +
  "    Reendering from Markup Code \n" +
  "</div>\n" +
  "</body>\n" +
  "</html>"
webView.loadData(htmlMarkup, "text/html", "UTF-8")

3. Loading content from hosted online.
webView.loadUrl("https://www.google.com")

WebView Settings


Applying WebView Settings .
Enabling JavaScript and ZoomControl
val webViewSettings = webView.settings
webViewSettings.javaScriptEnabled = true
webViewSettings.builtInZoomControls = true

WebViewClient callback


webViewClient has below callback

onPageStarted Notifies the page start event
onPageFinished Notifies the page end event
shouldOverrideUrlLoading 1. Give the host application a chance to take control
when a URL is about to be loaded in the current WebView
If a WebViewClient is not provided, by default
WebView will ask Activity Manager to choose the
proper handler for the URL .

2. Returning true causes the current WebView to
abort or stop loading the URL .

3. Returning false causes the current WebView to
continue loading the URL as usual

WebChromeClient


webChromeClient has below callback

onProgressChanged Tell the host application the current progress of loading a page.
onReceivedIcon Notify the host application of a new favicon for the current page.
onReceivedTitle Notify the host application of a change in the document or webpage title.

WebView Navigation


1. Back Navigation  

 canGoBack() : Gets whether this WebView has a back history item.
 goBack(): Goes back in the history of this WebView.

2. Forward Navigation

 canGoForward(): Gets whether this WebView has a forward history item.
 goForward() : Goes forward in the history of this WebView.

3. Handling WebView On Device BackPress.

Inside onBackPressed callback of activity check whether webview has back history , if yes call goBack on webvie else call  super.onBackPressed() .

override fun onBackPressed() {
 if (webView.canGoBack()) {
  webView.goBack()
 } else {
  super.onBackPressed()
 }
}

Activity

  1. Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
  2. Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml).
  3. Using webView reference apply webview settings and load url .
file : MainActivity.kt
package com.tutorialsbuzz.androidwebview

import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.navigator.*

class MainActivity : AppCompatActivity() {

    val TAG: String = MainActivity::class.java.simpleName

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        webView.loadUrl("https://www.google.com");

        val webViewSettings = webView.settings

        webViewSettings.javaScriptEnabled = true
        webViewSettings.builtInZoomControls = true
        
        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.d(TAG, "onPageStarted")
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.d(TAG, "onPageFinished")
            }

            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                return false
            }
        };

        webView.webChromeClient = object : WebChromeClient() {

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                Log.d(TAG, "onProgressChanged Progress $newProgress")
            }
        }

        navBack.setOnClickListener({ v ->
            if (webView.canGoBack())
                webView.goBack()
        })

        navFwd.setOnClickListener({ v ->
            if (webView.canGoForward())
                webView.goForward()
        })
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}


No comments:

Post a Comment