我浏览了很多网页以获取教程。我看到很多关于将 CSS/js 注入(inject)本地 HTML 文件的帖子。但我正在尝试将我的 CSS 文件注入(inject)到 android webview 元素的网页中。示例:将自定义字体 CSS 注入(inject) Facebook、Google 等...(不注入(inject)本地 HTML 文件)。我的代码不起作用。
这是我的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
String html = "<html><head><style>@font-face {@font-family: 'Conv_LISU'; src: url('file:///android_asset/font/LISU.ttf');} body, button, input, label, select, td, tr, textarea,li,ul,span,div,table,h1,h2,h3,h4{ font-family:Conv_LISU;}</style></head>";
WebView webView = (WebView)findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.loadData(html, "text/html", "utf-8");
webView.loadUrl("http://google.com");
}
最佳答案
这种方式不起作用,因为您的源字体来自/assets/文件夹。
String html = "<html><head><style>@font-face {@font-family: 'Conv_LISU'; src: url('file:///android_asset/font/LISU.ttf');} body, button, input, label, select, td, tr, textarea,li,ul,span,div,table,h1,h2,h3,h4{ font-family:Conv_LISU;}</style></head>";
当 CSS 不是来自互联网时,它不会获取字体,请将“src:url('file:///android_asset/font/LISU.ttf')”处的代码更改为一些可下载的字体链接,例如:“src:url("http://www.vonna.com/fonts/sahara01.ttf ")".
它现在应该可以工作了。
关于android - 将CSS注入(inject)android webview中的网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23533336/