I want to change WebView font. There are 2 files in "assets" folder. They are:
assets/fonts/DejaVuSans.ttf and
assets/css/result.css
I searched some answers on StackOverflow and find out a solution but it doesn't work. The result.css loads DejaVuSans.ttf using @font-face directive. Then it is included in < link > tag of data which is passed to WebView::loadDataWithBaseURL (The code is below). The problem is CSS styles works (the text is red) but the font doesn't. Square characters appears when I show phonetic symbols (/'pə:sn/).
String resultText = "<html><head>";
resultText += "<link href=\"css/result.css\"" + " rel=\"stylesheet\" type=\"text/css\" />";
resultText += "<style>" + "@font-face { font-family: \"DejaVuSans\"; " + "" +
"src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style>";
resultText += "</head>";
resultText += "<body><p>" + text + "</p>" + "</body></html>";
resultView.loadDataWithBaseURL("file:///android_asset/", resultText, "text/html", "utf-8", null);
result.css:
@font-face {
font-family: "DejaVuSans";
/*src: url('fonts/DejaVuSans.ttf'); also not work*/
src: url('file:///android_asset/fonts/DejaVuSans.ttf');
}
body {
color: red;
}
The System.out.println(resultText) is:
<html><head><link href="css/result.css" rel="stylesheet" type="text/css" /><style>@font-face { font-family: "DejaVuSans"; src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style></head><body><p>person /'pə:sn/</p></body></html>
It was solved. I didn't add "font-family" to body selector and font url must be file:///android_asset/fonts/DejaVuSans.ttf".
@font-face {
font-family: 'DejaVuSans';
/* src: url('DejaVuSans.ttf'); This doesn't work */
/* src: url('fonts/DejaVuSans.ttf'); Neither is this */
src: url('file:///android_asset/fonts/DejaVuSans.ttf'); /* but this does */
}
body {
font-family: 'DejaVuSans';
color: red;
}
Known bug on 2.0 and 2.1 :
http://code.google.com/p/android/issues/detail?id=4448
For 2.2 :
@font-face {
font-family: 'FontName';
src: url('filefont.ttf'); // with no "fonts/"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With