In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functionality of that of a browser like a search input, new tabs, incognito, etc.
In this article, we will show you how you could implement a WebView in Android using Jetpack Compose.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Step 2: Add Internet permission in the manifest file
Navigate to the app > manifests > AndroidManifest.xml file and add the following line of code under the <manifest> tag.
<uses-permission android:name="android.permission.INTERNET" />Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.*
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.viewinterop.AndroidView
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
// call composable
WebViewExample()
}
}
}
}
// composable with a AndroidView
@Composable
fun WebViewExample() {
// Declare a string that contains a url
val mUrl = "https://www.wikipedia.org/"
// Adding a WebView inside AndroidView with layout as full screen
AndroidView(factory = {
WebView(it).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = WebViewClient()
loadUrl(mUrl)
}
}, update = {
it.loadUrl(mUrl)
})
}