You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android WebView无法设置自定义字体且提示不允许加载本地资源问题问询

Android WebView加载res目录下自定义字体失效修复方案

错误根因

  • 使用loadData()方法加载HTML字符串时,WebView默认没有访问App本地资源的权限,你代码里写的file:///android_res/font/regular.ttf路径会被WebView的安全策略拦截,这就是控制台输出Not allowed to load local resource警告的直接原因
  • 你当前strings.xml中的HTML结构不完整,缺少</p>、</body>、</html>标签和CDATA闭合标记]]>,会导致HTML解析异常

修复步骤

1. 修正strings.xml中的HTML内容

补全标签闭合,同时将字体路径改为相对路径:

<string name="app_sample_text"><![CDATA[
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        @font-face {
            font-family: regular;
            src: url("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.</p>
</body>
</html>
]]></string>

2. 替换WebView加载方法

将loadData()替换为loadDataWithBaseURL(),指定baseUrl为本地res资源的根路径,让WebView可以识别HTML中的相对资源路径:

val text = getString(R.string.app_sample_text)
binding.webView.loadDataWithBaseURL("file:///android_res/", text, "text/html", "UTF-8", null)

3. 可选补充配置

如果仍然出现资源拦截警告,可以主动开启WebView的本地资源访问权限:

binding.webView.settings.apply {
    allowFileAccess = true
    allowContentAccess = true
}

内容的提问来源于stack exchange,提问作者Anshul Tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:15:07