- 确认自定义的字体文件(.ttf或.otf)已放置在res/font目录中。
- 创建一个自定义的WebViewClient并覆盖shouldInterceptRequest方法,用来拦截请求自定义字体的URL。
示例代码:
WebView myWebView = findViewById(R.id.myWebView);
myWebView.setWebViewClient(new WebViewClient() {
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains("file:///android_res/font/")) {
try {
InputStream inputStream = getApplicationContext().getAssets().open("font.ttf"); // 替换为自己想使用的字体文件
WebResourceResponse response = new WebResourceResponse("application/x-font-ttf", "UTF-8", inputStream);
return response;
} catch (IOException e) {
e.printStackTrace();
}
}
return super.shouldInterceptRequest(view, request);
}
});
- 在WebSettings中启用字体支持。
WebSettings webSettings = myWebView.getSettings();
webSettings.setAllowFileAccess(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);