Easy way to use Custom Fonts in Android WebViews

Photo by Brett Jordan from Pexels

Sometimes a backend provides you with a partial or unstyled html code, usually provenient from a Rich Text editor in a Web App. Therefore, you need to complete this html code and display it in a WebView. If you’re using a custom font, you might have noticed there’s no straightforward way to modify the default WebView font family, as there is for other views. Here’s an easy way to do it via CSS.

Let’s just assume you have a .ttf or an .otf file under your res/font directory. You can use the following code snippet to have a complete HTML you can load in a WebView. This method will NOT work for xml font family resources, as they're native to Android, and not web.

Then all you need to do is load the resulting html into your WebView:

Originally published at https://reul.space.