We have a view (screen 1) with an Android WebView ...
# compose
j
We have a view (screen 1) with an Android WebView embedded in it. We have a use case where we need to navigate to another screen (screen 2), then come back to the screen 1 with the WebView in it. We’re running into an issue with screen 1 recomposing and instantiating a new WebView. Since WebView is a little expensive to init, we were looking for a way to avoid reloading the WebView. I know it’s expected that screen 1 will go out of composition when you navigate away from it, but wanted to see if there are options to avoid that in this case. More in 🧵
The approach that we’re currently going with is to not navigate away at all and display the contents of Screen 2 over our WebView instead. This is real easy to do with Compose and may be the best approach, but just wanted to check if there were better options.
c
You could keep a reference to the WebView in your Activity. Whether or not that makes sense depends on how long you want to keep it around. Roughly…
Copy code
class MyActivity : Activity() {
  val webview: WebView = ...

  override fun onCreate() {
    setContent {
      AndroidView(factory = { webview })
    }
  }
}
j
ah interesting, We’re single activity right now and only need the webView for this one screen out of many so I wouldn’t want to hang on to it for the life time of the app.
It did not occur to me that we can pass the existing WebView into AndroidView, though. We’re using the WebView Composable from the Accompanists library and it doesn’t expose that parameter. That may be helpful for us.
c
I do this in my app although my use case is slightly different; I’m passing a SurfaceView to show the camera preview, and it remains on-screen almost all the time. As an alternative could could
remember
the WebView in a parent composable, and pass it to the child screen that needs it. I can’t confirm this is a good idea; I haven’t tested or inquired about that.