When wrapping a `WebView` in an `AndroidView` for ...
# compose
j
When wrapping a
WebView
in an
AndroidView
for use in a compose app, I have need of methods on the webview instance outside of the wrapped component for example a refresh button that calls
webView.loadUrl(…)
. How do I expose this to composable functions using the
WebView
component? Unsure how to expose this from the wrapped component
t
maybe something like this?
Copy code
@Composable
fun WebViewWrapper(url: String?, modifier: Modifier = Modifier) {
    AndroidView(
        factory = { context ->
            android.webkit.WebView(context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                // set up webview
                if (url != null) loadUrl(url)
            }
        },
        update = { innerWebView ->
            if (url != null) {
                innerWebView.loadUrl(url)
            }
        }
    )
}
basically converting the imperative
webView.loadUrl()
into a declarative/state-based functionality
(sidenote: the match parent stuff is there because of https://issuetracker.google.com/issues/190411390)
For the other apis maybe have to treat them as state as well -
webView.reload
/
goForward/Backward
etc
j
Thanks @Tash, the match parent layout sidenote fixed another issue so appreciate that very much! If I wanted to put that
WebViewWrapper
composable in a
Column
with a button that called
webView.loadUrl()
in
onClick
do you have any examples on how you would expose the WebView instance to
onClick
in that scenario? I had solved this by keeping a reference to
WebView
in my viewmodel, however this feels wrong 😅
Copy code
@Composable
fun SomeColumn() {
    WebViewWrapper()
    Button(onClick = { ^trigger WebView.loadUrl() somehow }
}
Just saw the accompanist webview wrapper implementation which helped me understand it better https://github.com/google/accompanist/commit/c4f721e2d51f2c81a1c4be971e1b3847b13d001c
👍🏼 1
c
accompanist has a webview sample? ooh. TIL. This would've been helpful last week. 😂
😆 1
307 Views