Android WebView 网页使用本地字体

要求在网页里面调用android app中assets目录下的某个字体文件。

网页加载通常有两种方式:
1、loadDataWithBaseURL
2、loadUrl

一、loadDataWithBaseURL

网页中直接使用file://指定assets文件路径即可

示例:

font-family: url('file:///android_asset/xxx.TTF')

二、loadUrl

这种情况网页中不能直接使用file://来指定文件路径,否则会如下错误。

"Not allowed to load local resource: file:///android_asset/fonts/xxx.TTF"

正确做法:必须通过WebView来拦截。

1、在网页中指定字体

font-family: url('/android_asset_font/xxx.TTF')

2、重写WebViewClient 的shouldInterceptRequest方法

		String INJECTION_TOKEN = "/android_asset_font/";

		@Override
		public WebResourceResponse shouldInterceptRequest(WebView webView, String url) {
			if (url != null && url.contains(INJECTION_TOKEN)) {
				try {
					String assetPath = url.substring(url.indexOf(INJECTION_TOKEN) + INJECTION_TOKEN.length(), url.length());
					return new WebResourceResponse(
							"application/octet-stream",
							"UTF8", getContext().getAssets().open(assetPath)
					);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return super.shouldInterceptRequest(webView, url);
		}

参考:
https://stackoverflow.com/questions/19997146/kitkat-kills-not-allowed-to-load-local-resource-file-android-asset-webkit-a/20992306#20992306

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值