Skip to main content

Zooming the Android WebView in Xamarin.Forms

·3 mins

Oops, I did it again… Another PR got merged into Xamarin.Forms, this time adding the ability to set op zooming on the WebView on Android. In this post, I will show you what was added and how you can use it.

Everybody was WebView zooming, ha! #

Before this change, it was only possible to enable zooming on Android by implementing a custom renderer. Now, a new API was introduced to make this possible straight from Xamarin.Forms. Have a look at the code underneath.

EnableZoomControls #

And actually, that is all there is to it. With the EnableZoomControls you enable the zooming capabilities without showing any dedicated controls for it. You can now zoom by using the pinch and pan gesture in a WebView. The result can be seen underneath.

WebView EnableZoomControls

WebView EnableZoomControls

DisplayZoomControls #

To also display on-screen zoom controls for the user, you can use DisplayZoomControls. With this method, a control is shown in the corner of the WebView, which allows the user to zoom in or out by tapping one of the options. You can see this in action underneath. Note the visible zoom controls in the bottom-right.

WebView DisplayZoomControls

WebView DisplayZoomControls

Note that DisplayZoomControls only has use when EnableZoomControls has been set to true as well.

A bit of background #

Let me tell you a little bit about what is going on behind the scenes. What happens is that the true or false that you now set on the Forms WebView is transferred to the native Android WebView. Underneath you can find a code snippet of the actual implementation.

I simply set a couple of properties on the Android native control based on the values I get through from Xamarin.Forms. I have implemented a little check on certain API levels, although those don’t seem to be relevant anymore nowadays, or at least I hope no one is using those anymore.

The Android naming and working is a bit confusing in my opinion. It took me some time to figure out that SetSupportZoom and BuiltInZoomControls should be used together. I feel like BuiltInZoomControls already implies that the zoom control would show, but that is not the case. Only when you set DisplayZoomControls the actual controls are displayed, the rest is just to enable zooming in general.

Wrapping up #

When the new version of Xamarin.Forms is coming out, probably version 3.6 4.0, this will be available for you to use. This together with some other features I have built into the Forms toolkit should be available shortly.

There are a lot of issues still open on the Xamarin.Forms repository, so if you’d like to contribute something yourself, this is your chance! I am happy to help if you have any questions or need some help in any other way. For me for now, on to the next PR!