要求在网页里面调用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