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 cus
i done this by upper answers with this additions:
webView.loadDataWithBaseURL("file:///android_asset/",
WebClient.getStyledFont(someText),
"text/html; charset=UTF-8", null, "about:blank");
and then use 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>" : "");
}
thanks to everybody:)
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);
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);
The issue is it needs to be in a folder, try putting "./myfont.ttf" instead, if not put the font inside a folder in assets like "fonts/myfont.ttf" that will work for sure.
test it, work for me like a charm :
private void setResult() {
String mimeType = "text/html;charset=UTF-8";
String encoding = "utf-8";
String htmlText = htmlPrivacy;
String text = "<html><head>"
+ "<style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/fonts/iy_reg.ttf\")}body{font-family: MyFont;color: #666666}"
+ "</style></head>"
+ "<body>"
+ htmlText
+ "</body></html>";
webView.loadDataWithBaseURL(null, text, mimeType, encoding, null);
}
This is how do you load htmlData in a webview:
webview.loadDataWithBaseURL(null, getHtmlData(activity,**htmlData**) , "text/html", "utf-8", "about:blank");
where getHtmlData(activity,**htmlData**)
returns a string of html code.