-1

I have a webview loaded with HTML data. I want to be able to change the font of the HTML at runtime. For this I have a setting where the user can choose a font (the fonts are taken from the /system/fonts directory).

font selector

How do I apply the selected font to the webview?

I tried this by using javascript:

String fontString = "font-family: 'myFont'; url: /system/fonts/DroidSans.ttf;";
if (android.os.Build.VERSION.SDK_INT < 19) {
    webview.loadUrl("javascript:changeStyle('body', '" + fontString + "')");
} else {
    webview.evaluateJavascript("javascript:changeStyle('body', '" + fontString + "')", null);
}

With changeStyle() defined in the HTML's javascript:

function changeStyle(tag, style) {
    var myList = document.getElementsByTagName(tag); // get all p elements
    var x = myList.length;
    myList[0].setAttribute("style", style);
}

This is, however, not working. I'm pretty sure there is nothing wrong with the changeStyle() js-function, for it is working to set the font size or color.

Community
  • 1
  • 1
Skywalker10
  • 939
  • 3
  • 9
  • 21

1 Answers1

0

Dont use setAttribute to change the style: https://stackoverflow.com/a/6065647/3556874

You can set the style for font like this

myList[0].style.font = FontStyle;

and pass the style in this format to the changeStyle funtion, FontStyle="italic bold 22px arial,serif"; or whatever you font maybe

Community
  • 1
  • 1
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
  • This doesn't explain how to apply the system fonts to the webview. Arial for example is not one of the system fonts. If I put roboto as the font, nothing happens. – Skywalker10 Feb 10 '15 at 11:17
  • how to use custom fonts is a different question!! This answer explains how to correctly apply font dynamically.. if you want to learn how to use custom fonts read this http://www.w3schools.com/cssref/css3_pr_font-face_rule.asp, Or you may include the corresponding font file in your project. – Naeem Shaikh Feb 10 '15 at 11:31