Monday, October 18, 2021

jetpack compose - How to use WebView

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedObjectState: Bundle?) {
        super.onCreate(savedObjectState)
        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text(
                        text = "Compose - Using WebView"
                    )},
                    backgroundColor = Color(0xFFC0E8D5),
                )
            },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0),
        )
    }


    @Composable
    fun MainContent(){
        val url = remember { mutableStateOf("https://www.google.com")}
        Box(
            modifier = Modifier.fillMaxSize(),
        ){
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .weight(2F)
                ) {
                    AndroidView(factory = { context ->
                        WebView(context).apply {
                            applySettings()
                            loadUrl("https://www.google.com")
                        }
                    },update = {
                        it.loadUrl(url.value)
                    })
                }

                Row(
                    modifier = Modifier
                        .padding(8.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .wrapContentHeight(Alignment.CenterVertically),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(onClick = {
                        url.value = "https://www.google.com"
                    }) {
                        Text(text = "Google")
                    }
                    Button(onClick = {
                        url.value = "https://www.yahoo.com"
                    }) {
                        Text(text = "Yahoo")
                    }
                    Button(onClick = {
                        url.value = "https://example.com"

                    }) {
                        Text(text = "Example")
                    }
                }
            }
        }
    }
}


// extension method to apply web view settings
fun WebView.applySettings(){
    val layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT
    )
    // or use this
    val linearlayoutParams = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    )
    this.layoutParams = layoutParams

    //clearCache(true)
    clearCache(true)

    // Get the web view settings instance
    val settings = 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(context.cacheDir.path)

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

    // Zoom web view text
    settings.textZoom = 100

    // 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
    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)
    settings.allowUniversalAccessFromFileURLs = true
    settings.allowFileAccess = true

    // WebView settings
    fitsSystemWindows = true
    setLayerType(View.LAYER_TYPE_HARDWARE, null)
}