如何在Android中更改Webview的字体? [英] How to change font face of Webview in Android?

查看:116
本文介绍了如何在Android中更改Webview的字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 webview 的默认字体更改为自定义字体.我正在使用 webview 为 Android 开发双语浏览器应用.

I want change the default font of webview to a custom font. I'm using webview in developing an bilingual browser app for Android.

我尝试通过将我的自定义字体放在资产中来获取自定义字体的实例.但是仍然无法将 webview 的默认字体设置为我的字体.

I tried getting an instance of custom typeface by placing my custom font in assets. But still couldn't set webview's default font to my font.

这是我试过的:

Typeface font = Typeface.createFromAsset(getAssets(), "myfont.ttf"); 
private WebView webview;
WebSettings webSettings = webView.getSettings();
webSettings.setFixedFontFamily(font);

任何人都可以更正此问题或建议任何其他方法将 webview 的默认字体更改为自定义字体吗?

Can anyone correct this or suggest any other method to change webview's default font to a custom font?

谢谢!

推荐答案

这个项目.归结为:

  1. 在您的 assets/fonts 文件夹中,放置所需的 OTF 或 TTF 字体(此处为 MyFont.otf)
  2. assets 文件夹内(此处位于 assets/demo/my_page.html 内)创建一个用于 WebView 内容的 HTML 文件:

  1. In your assets/fonts folder, place the desired OTF or TTF font (here MyFont.otf)
  2. Create a HTML file that you'll use for the WebView's content, inside the assets folder (here inside assets/demo/my_page.html):

<html>
<head>
<style type="text/css">
@font-face {
    font-family: MyFont;
    src: url("file:///android_asset/fonts/MyFont.otf")
}
body {
    font-family: MyFont;
    font-size: medium;
    text-align: justify;
}
</style>
</head>
<body>
Your text can go here! Your text can go here! Your text can go here!
</body>
</html>

  • 从代码中将 HTML 加载到 WebView 中:

  • Load the HTML into the WebView from code:

    webview.loadUrl("file:///android_asset/demo/my_page.html");
    

  • 请注意,不允许通过 loadData() 注入 HTML.作为根据文档:

    Take note that injecting the HTML through loadData() is not permitted. As per the documentation:

    请注意,JavaScript 的同源策略意味着在使用此方法加载的页面中运行的脚本将无法访问使用除数据"以外的任何方案加载的内容,包括http(s)".为避免此限制,请将 loadDataWithBaseURL() 与适当的基本 URL 结合使用.

    Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

    正如@JaakL 在下面的评论中所建议的,要从字符串加载 HTML,您应该提供指向您的资产的基本 URL:

    As @JaakL suggests in the comment below, for loading HTML from a string, you should instead provide the base URL pointing to your assets:

    webView.loadDataWithBaseURL("file:///android_asset/", htmlData);
    

    htmlData 中引用字体时,您可以简单地使用 /fonts/MyFont.otf(省略基本 URL).

    When referencing the font in htmlData, you may then simply use /fonts/MyFont.otf (omitting the base URL).

    这篇关于如何在Android中更改Webview的字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆