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:
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.
Many of the above answers work lie a charm if you have your content in your assets folder.
However, if you like me want to download and save all your assets from a server to your internal storage you can instead use loadDataWithBaseURL and use a reference to your internal storage as the baseUrl. Then all files there will be relative to the loaded html and are found and used correctly.
In my internal storage I have saved the following files:
IndigoAntiqua2Text-Regular.ttf
style.css
image.png
Then I use the following code:
WebView web = (WebView)findViewById(R.id.webby); //For avoiding a weird error message web.setLayerType(View.LAYER_TYPE_SOFTWARE, null); String webContent = "" + "
I have only tried this while targeting minSdkVersion 19 (4.4) so I have no idea if it works on other versions
回答7:
You can do it by using CSS. I did it with an app but it won't work in Android 2.1 as there is an known bug with Android browser 2.1.
回答8:
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.