Search code examples
androidandroid-webview

Unable to change custom res/font in Android WebView


I'm loading a string from strings.xml in android WebView with custom font but unable to see change on UI. Instead of that I get a warning in console as:

[INFO:CONSOLE(0)] "Not allowed to load local resource: file:///android_res/font/regular.ttf"

strings.xml

 <string name="app_sample_text">"<![CDATA[
 <!DOCTYPE html><html><head>
 <style type="text/css">
 @font-face {
 font-family: regular;
 src: url("file:///android_res/font/regular.ttf")
 }
 body {
 font-family: regular;
 font-size: medium;
 text-align: justify;
 }
 </style>
 </head><body><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
"</string>

In WebView, loading as:

   val text = getString(R.string.app_sample_text)
   binding.webView.loadData(text, MIME_TYPE, ENCODING)

Path of .ttf file is res/font/regular.ttf

But still, I'm seeing default font of WebView. Please let me know if I'm doing any mistake.


Solution

  • Found solution of the problem by using WebViewAssetLoader:

    val assetLoader = activity?.let { WebViewAssetLoader.ResourcesPathHandler(it) }?.let {
            WebViewAssetLoader.Builder()
                .addPathHandler(WEBVIEW_RES_PATH_HANDLER, it)
                .build()
        }
    
        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest
            ): WebResourceResponse? {
                return assetLoader?.shouldInterceptRequest(request.url)
            }
        }
        binding.webView.loadDataWithBaseURL(WEBVIEW_BASE_URL, text, MIME_TYPE, ENCODING, null)
    }
    
    companion object {
        const val WEBVIEW_RES_PATH_HANDLER = "/res/"
        const val WEBVIEW_BASE_URL = "https://appassets.androidplatform.net"
    }