Building a Application in Jetpack Compose with WebView | by Vivek Yadav | Nov, 2024

Here’s the code snippet we’ll be discussing:

package com.create.nativenews.view

import android.webkit.WebView
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView

@Composable
fun NewsArticlePage(url: String, title: String) {
// AndroidView allows us to use traditional Android Views in Compose
AndroidView(
factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.loadsImagesAutomatically = true
settings.mixedContentMode = 0
loadUrl(url)
}
}
)
}

  1. Package Declaration:
package com.create.nativenews.view

This line declares the package for the NewsArticlePage composable function, organizing your code into a modular structure.

2. Composable Function:

@Composable
fun NewsArticlePage(url: String, title: String) {

3 Using AndroidView:

AndroidView(
factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.loadsImagesAutomatically = true
settings.mixedContentMode = 0
loadUrl(url)
}
}
)
  • AndroidView: This composable allows us to embed traditional Android views into a Compose UI. The factory lambda is where we create the WebView.

Leave a Reply