java - 更改字体 WebView Android Studio

标签 java android html webview

我遇到了 HTML 问题:我想在 Web View 中使用自定义字体,但它不会使用以下代码更改字体:

 public void loadHTLMContentText(String text, WebView view) {

    String body;
    String head = "<head><style type=\"text/css\">\n" +
            "@font-face {\n" +
            "    font-family: Bamini;\n" +
            "    src: url(\"Bamini.ttf\")\n" +
            "}\n" +
            "body {\n" +
            "    font-family: Bamini;\n" +
            "    font-size: medium;\n" +
            "    text-align: justify;\n" +
            "}\n" +
            "</style></head>";
    if (text != null) {
        body = text;
    } else return;
    String htmlData = "<html>" + head + "<body style=\"font-family: bamini\">" + body + "</body></html>";


    view.loadData(htmlData, "text/html; charset=utf-8", "utf-8");
    view.setBackgroundColor(0x00000000);

}

ttf 文件与 .java 位于同一文件夹中。

layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        HTMLPre preparer = new HTMLPre();


        View one = layoutInflater.inflate(R.layout.slide_type_a, container, false);


        WebView header_1_a = (WebView) one.findViewById(R.id.header_slide_type_a_1);
        preparer.loadHTLMContentHeader(getString(R.string.Historie1_header),header_1_a);

有什么建议吗?

最佳答案

The ttf-file is in the same folder as the .java

这毫无意义,原因有两个:

  • Android 通常不会将随机文件与 Java 类一起使用

  • WebView 无论如何都不知道这些

创建一个 src/main/assets/ 目录(假设您正在典型的 Android Studio 项目中工作)。将您的字体文件放在那里。使用 loadDataWithBaseURL(),并使用 file:///android_asset/ 作为 URL。然后,希望一切顺利。

关于java - 更改字体 WebView Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42775367/

相关文章:

java - Android Volley POST 服务器错误

java - 如何使用注释在 spring batch 中运行多个作业

css - 绝对定位按钮不会出现在固定标题上

html - CSS 自动高度和宽度建议

java - Checkstyle 插件不关心外部配置文件中的内容

Java内存收集使用

java - 为 BLE 秤编写应用程序代码 - 包含所有信息

android - 在应用的发行版中,三星设备中未生成FCM token

android - 在Activity中使用ArrayList作为fragment中RecyclerView Adapter的内容

html - CSS使用div创建均匀间隔的表格