Compose WebView Part 4 | OFFLINE Load from Assets folder
We learn online webview to load a webpage/website from URL online. We can also load a webpage from the assets folder in jetpack compose webview.
You can provide web-based content—such as HTML, JavaScript, and CSS—for your app to use that you statically compile into the application rather than fetch over the internet.
This example demonstrates how do I load files from asset directory into WebView in android.
Step 1:
To add text-based web files to a project, do the following:
In Android Studio, right-click the app > src > main folder and then choose New > Directory.
Name the folder "assets."
Right-click the assets folder and then click New > File. Enter
index.html
and press Return or Enter.Fill in the empty files with the web files (Html, CSS, JS).
Step 2:
package com.blogspot.boltuix
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WebViewPage("file:///android_asset/index.html") //OFFLINE
}
}
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebViewPage(url: String){
// 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()
// to play video on a web view
settings.javaScriptEnabled = true
// to verify that the client requesting your web page is actually your Android app.
settings.userAgentString = System.getProperty("http.agent") //Dalvik/2.1.0 (Linux; U; Android 11; M2012K11I Build/RKQ1.201112.002)
loadUrl(url)
}
}, update = {
it.loadUrl(url)
})
}
..
GET full source code on Gumroad:
Comments
Post a Comment