Using Webview in Jetpack Compose and enforce Dark Mode
Webview is an important part of Android Development. From our small News App news page to Corporate App content page, it is great and easy to implement. It is highly in use. In this mini-blog, I will show you how to implement Webview with Jetpack Compose
It is really simple and doesn’t require any additional dependency. It is not available with Compose we will be using AndroidView to implement it. Let’s see the code
* AndroidView - It is commonly needed for using Views that are infeasible to be reimplemented in Compose and there is no corresponding Compose API.* layoutParams - It is used to set the dimentions of the view. Here we are setting it to match parent* loadUrl()- In this function we pass the url string which is to be fetched.
* webViewClient - Here we add the WebViewClient(). Give the host application a chance to take control when a URL is about to be loaded in the current WebView. If a WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the URL. If a WebViewClient is provided, returning true causes the current WebView to abort loading the URL, while returning false causes the WebView to continue loading the URL as usual.
Yes, That’s it. It is all you need to implement webview in Jetpack Compose, use this component anywhere according to your requirement.
Implementing Dark Mode in WebView
For this, we need to add the WebKit dependency which is from androidx. It has much more features and settings that you can play around with. We will focus on implementing Dark Mode.
This is almost the same as the above implementation but we have just added a small condition block. I forgot to mention it requires Android Q.
We are just checking if the feature is supported, i.e. our FORCE_DARK then just setting force dark as FORCE_DARK_ON to the
That’s it it is really simple to implement webview in android with Compose. Hope you liked it.
I will well appreciate one of these 👏