我有一个android webview,其中的文字有sans-serif字体。我在assets / sans-serif.ttf中有ttf文件 这是代码
WebView webVw;
String webContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webVw=(WebView)findViewById(R.id.webVw);
webContent="%3Cdiv%20style%3D%22width%3A100%25%3Bheight%3A100%25%3Bposition%3Arelative%3Bleft%3A.1%25%3Btop%3A.1%25%22%3E%3Cdiv%20style%3D%22position%3Aabsolute%3Bwidth%3A31%25%3Bheight%3A42.22222222222222%25%3Bleft%3A36.375%25%3Btop%3A19.02313624678663%25%3Bcolor%3Argb(0%2C%200%2C%200)%3Bfont-size%3A50px%3Bfont-style%3Anormal%3Bfont-family%3Asans-serif%2C%20sans-serif%2C%20sans-serif%3Bfont-weight%3A400%22%20%3EOverlay!%20%3C%2Fdiv%3E%3Ca%20href%3D%22javascript%3A%20void(0)%22%20%20target%3D%22_blank%22%20%3E%3Cimg%20src%3D%22https%3A%2F%2Fsi0.twimg.com%2Fprofile_images%2F1490344068%2FLOGO_COGNIZANT_C_only_normal.jpg%22%20style%3D%22position%3Aabsolute%3Bwidth%3A4.875%25%3Bheight%3A10.444444444444445%25%3Bleft%3A0.625%25%3Btop%3A1.2853470437017995%25%22%20%2F%3E%3C%2Fa%3E%3Cdiv%20style%3D%22position%3Aabsolute%3Bwidth%3A4%25%3Bheight%3A6.666666666666667%25%3Bleft%3A95%25%3Btop%3A1.5424164524421593%25%3Bbackground%3Argb(47%2C%206%2C%20246)%20none%22%20%3E%3C%2Fdiv%3E%3Cdiv%20class%3D%22cf-component%20buttonwrap%22%20style%3D%22position%3Aabsolute%3Bborder%3Dradius%3A5px%3Bwidth%3A4.25%25%3Bheight%3A4.222222222222222%25%3Bleft%3A6.125%25%3Btop%3A3.3419023136246784%25%3Bbackground%3Argb(6%2C%20115%2C%20233)%3Bfont-size%3A15px%3Bfont-style%3Anormal%3Bfont-family%3Asans-serif%2C%20sans-serif%2C%20sans-serif%3Bfont-weight%3A400%22%20%3E%3Ca%20%20class%3D%22editableTxt%22%20href%3D%22http%3A%2F%2Fwww.cognizant.com%22%20target%3D%22_blank%22%3E%20Go!%3C%2Fa%3E%3C%2Fdiv%3E%3C%2Fdiv%3E";
String head="<head><style>@font-face {font-family: 'sans-serif';src: url('file:///assets/sans-serif.ttf');}body {font-family: 'sans-serif';}</style></head>";
String HtmlString = "<html>"+head+"<body>"+webContent+"</body></html>";
webVw.loadData(HtmlString, "text/html","charset=UTF-8");
}
webview显示正常字体但不显示sans-serif
答案 0 :(得分:1)
试试这个......
在您的assets / fonts文件夹中,放置所需的OTF或TTF字体(此处为MyFont.otf) 在assets文件夹中创建一个用于WebView内容的HTML文件(此处位于assets / 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>
从代码中将HTML加载到WebView中:
webview.loadUrl("file:///android_asset/demo/my_page.html");
请注意,通过loadData()注入HTML对我来说不起作用。我很想知道是否有人可以让它发挥作用。
答案 1 :(得分:0)
使用此代码而不是
webVw.loadDataWithBaseURL("file:///android_asset/",HtmlString, "text/html", "UTF-8",null);
答案 2 :(得分:0)
在某些情况下,如果您尝试了很多方法来解决此问题,但您还没有解决问题。您应该尝试检查您的字体文件是否正确名称。打开您的字体文件并检查字体名称,复制该文件并将文件重命名为正确的名称。 在您的HTML代码中也使用正确的名称。 我有好几次这个问题!