CodexBloom - Programming Q&A Platform

Unexpected Behavior When Using AndroidView in Jetpack Compose for Custom WebView Implementation

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
android jetpack-compose webview kotlin

I'm relatively new to this, so bear with me. I'm facing an issue while trying to integrate a custom WebView in my Jetpack Compose application using `AndroidView`. The WebView should load a local HTML file and respond to certain JavaScript functions, but I notice that the WebView doesn't seem to retain its state after orientation changes. Initially, I set it up like this: ```kotlin @Composable fun CustomWebView(url: String) { val context = LocalContext.current AndroidView(factory = { WebView(context).apply { settings.javaScriptEnabled = true loadUrl(url) }}, update = { webView -> webView.loadUrl(url) }) } ``` The problem arises when I rotate the device; the WebView loses the previously loaded content and doesn't retain the JavaScript state. I've tried adding `android:configChanges="orientation|screenSize"` in the AndroidManifest.xml file for the activity, but that doesn’t seem to help. Furthermore, I also attempted to save the WebView state in `onSaveInstanceState` but ran into issues with the `Bundle` being null during the recreation of the activity. Here's my attempt at saving the state: ```kotlin override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val webViewBundle = Bundle() // Attempt to store WebView state webView.saveState(webViewBundle) outState.putBundle("webViewState", webViewBundle) } ``` However, during the `onCreate` method, I tried to restore it like this: ```kotlin override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val webViewState = savedInstanceState?.getBundle("webViewState") webView?.restoreState(webViewState) } ``` I keep getting a `NullPointerException` on `webView.restoreState(webViewState)` because `webView` seems to be re-instantiated before the state can be restored. What's the best approach here to ensure that the WebView maintains its state across configuration changes in a Compose environment? Any insights or best practices would be greatly appreciated! Thanks in advance!