How to change font face of Webview in 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.
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.
This is what I tried:
Typeface font = Typeface.createFromAsset(getAssets(), "myfont.ttf");
private WebView webview;
WebSettings webSettings = webView.getSettings();
webSettings.setFixedFontFamily(font);
Can anyone correct this or suggest any other method to change webview's default font to a custom font?
Thanks!
There's a working example of this in this project. It boils down to:
- In your
assets/fonts
folder, place the desired OTF or TTF font (here MyFont.otf) -
Create a HTML file that you'll use for the WebView's content, inside the
assets
folder (here insideassets/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>
-
Load the HTML into the WebView from code:
webview.loadUrl("file:///android_asset/demo/my_page.html");
Take note that injecting the HTML through loadData()
is not permitted. As per the documentation:
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.
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);
When referencing the font in htmlData
, you may then simply use /fonts/MyFont.otf
(omitting the base URL).
I am using this code :
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);
Even simpler, you can use the Asset URL format to reference the font. No programming needed!
@font-face {
font-family: 'myface';
src: url('file:///android_asset/fonts/myfont.ttf');
}
body {
font-family: 'myface', serif;
...
It can be done in Android. I took three days to solve this issue. But now it seems very easy. Follow these steps to set custom font for Webview
1.Add your font to assets folder
2.Copy the font to application's files directory
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;
}
3.You have to call above function only once (you have to find some logic for this).
copyFile(getContext(), "myfont.ttf");
4.Use the below code to set value for your webview. Here I am using CSS to set font.
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.You can call the above function as below
webview.loadDataWithBaseURL(null, getHtmlData(activity,htmlData) , "text/html", "utf-8", "about:blank");