如何在Android中更改Webview的字体?

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

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

这是我试过的:

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

任何人都可以改正这个或build议任何其他方法来改变webview的默认字体为自定义字体?

谢谢!

这个项目中有一个工作的例子。 归结为:

  1. assets/fonts文件夹中,放置所需的OTF或TTF字体(这里是MyFont.otf)
  2. assets文件夹(在assets/demo/my_page.html )中创build一个HTML文件,用于WebView的内容:

     <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> 
  3. 从代码中将HTML加载到WebView中:

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

请注意,不允许通过loadData()注入HTML。 根据文件 :

请注意,JavaScript的同源策略意味着使用此方法加载的页面中运行的脚本将无法访问使用'data'之外的任何scheme加载的内容,包括'http(s)'。 为避免这种限制,请使用loadDataWithBaseURL()和适当的基本URL。

正如@JaakL在下面的评论中所build议的,为了从一个string中加载HTML,你应该提供指向你的资源的基本URL:

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

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

我正在使用这个代码

 wv = (WebView) findViewById(R.id.webView1); String pish = "<html><head><style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/font/BMitra.ttf\")}body {font-family: MyFont;font-size: medium;text-align: justify;}</style></head><body>"; String pas = "</body></html>"; String myHtmlString = pish + YourTxext + pas; wv.loadDataWithBaseURL(null,myHtmlString, "text/html", "UTF-8", null); 

更简单的是,您可以使用资源URL格式来引用字体。 无需编程!

 @font-face { font-family: 'myface'; src: url('file:///android_asset/fonts/myfont.ttf'); } body { font-family: 'myface', serif; 

它可以在Android中完成。 我花了三天的时间来解决这个问题。 但现在看起来很容易。 按照以下步骤设置Webview的自定义字体

1.将您的字体添加到资产文件夹
2.将字体复制到应用程序的文件目录

 private boolean copyFile(Context context,String fileName) { boolean status = false; try { FileOutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE); InputStream in = context.getAssets().open(fileName); // Transfer bytes from the input file to the output file byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Close the streams out.close(); in.close(); status = true; } catch (Exception e) { System.out.println("Exception in copyFile:: "+e.getMessage()); status = false; } System.out.println("copyFile Status:: "+status); return status; } 

你只能调用一次以上的函数(你必须find这个逻辑)。

 copyFile(getContext(), "myfont.ttf"); 

4.使用下面的代码来为你的webview设置值。 在这里我使用CSS来设置字体。

 private String getHtmlData(Context context, String data){ String head = "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ context.getFilesDir().getAbsolutePath()+ "/verdana.ttf');}body {font-family: 'verdana';}</style></head>"; String htmlData= "<html>"+head+"<body>"+data+"</body></html>" ; return htmlData; } 

5.您可以拨打以上function

 webview.loadDataWithBaseURL(null, getHtmlData(activity,htmlData) , "text/html", "utf-8", "about:blank"); 

如果您的资源文件夹中有您的内容,上述答案中的许多工作将会很有魅力。

但是,如果你喜欢我想下载并保存所有的资源从服务器到你的内部存储,你可以改为使用loadDataWithBaseURL并使用一个对你的内部存储器的引用作为baseUrl。 然后,所有文件将相对于加载的HTML,并find并正确使用。

在我的内部存储器中,我保存了以下文件:

  • IndigoAntiqua2Text-Regular.ttf
  • style.css文件
  • image.png

然后我使用下面的代码:

 WebView web = (WebView)findViewById(R.id.webby); //For avoiding a weird error message web.setLayerType(View.LAYER_TYPE_SOFTWARE, null); String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>" + "<body><img src='image.png' width=\"100px\"><div class=\"running\">I am a text rendered with INDIGO</div></body></html>"; String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/"; web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", ""); 

上面的html(style.css)中使用的CSS文件:

 @font-face { font-family: 'MyCustomRunning'; src: url('IndigoAntiqua2Text-Regular.ttf') format('truetype'); } .running{ color: #565656; font-family: "MyCustomRunning"; font-size: 48px; } 

我只瞄准了minSdkVersion 19(4.4),所以我不知道它是否适用于其他版本

我做了这个更高的答案,这个补充:

 webView.loadDataWithBaseURL("file:///android_asset/", WebClient.getStyledFont(someText), "text/html; charset=UTF-8", null, "about:blank"); 

然后使用src: url("file:///android_asset/fonts/YourFont...

 public static String getStyledFont(String html) { boolean addBodyStart = !html.toLowerCase().contains("<body>"); boolean addBodyEnd = !html.toLowerCase().contains("</body"); return "<style type=\"text/css\">@font-face {font-family: CustomFont;" + "src: url(\"file:///android_asset/fonts/Brandon_reg.otf\")}" + "body {font-family: CustomFont;font-size: medium;text-align: justify;}</style>" + (addBodyStart ? "<body>" : "") + html + (addBodyEnd ? "</body>" : ""); } 

感谢大家:)

你可以通过使用CSS来完成。 我做了一个应用程序,但它不会在Android 2.1的工作,因为有一个已知的Android浏览器2.1的错误。

问题是它需要在一个文件夹中,试着把“./myfont.ttf”代替,如果没有把字体放在像“fonts / myfont.ttf”这样的资源文件夹中,那肯定会工作。

  webview= (WebView) findViewById(R.id.webview); String myCustomStyleString="<style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/fonts/iranian_sans.ttf\")}body,* {font-family: MyFont; font-size: 13px;text-align: justify;}img{max-width:100%;height:auto; border-radius: 8px;}</style>"; webview.loadDataWithBaseURL("", myCustomStyleString+"<div style=\"direction:rtl\">"+intentpost.getStringExtra("content")+"</div>", "text/html", "utf-8", null); 

这是你如何在webview中加载htmlData:

 webview.loadDataWithBaseURL(null, getHtmlData(activity,**htmlData**) , "text/html", "utf-8", "about:blank"); 

其中getHtmlData(activity,**htmlData**)返回一个html代码的string。