导语:
今天在项目中遇到一个小问题,就是webview作为容器盛放img时候的前缀和如何居中问题,如何解决呢,接下来就说说我解决步骤吧。
1.第一步,我想通过设置webview 参数控制webview内容中的img头部,没想到还真有这个方法,上代码:
String baseUrl = "http://m.fanai.com";
String html= "<img src="/upload/201606/18/201605181203083693.gif" alt="" />";
contentWeb.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null);
这样之后是可以的效果相当于是加载了<img src="http://m.fanai.com/upload/201606/18/201605181203083693.gif" alt="" />这么个webView可以完全释读的标签,然后加载出来后,效果并不十分理想,因为直接加载原图图片的大小,肯定要大于手机屏幕,然后我又去阅读那些前辈们的文章,全部都异口同声说有那么两个方法,上代码:
1.web.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
2.web.getSettings().setLoadWithOverviewMode(true);
但是经这么一设置后,效果是有了,但是还是不理想,图片全部缩小而且靠左边显示了,最后我开动脑筋,加了一段普通的CSS控制,问题得到完美解决。
重要代码:
contentWeb = (WebView) findViewById(R.id.notice_content_content);
contentWeb.getSettings().setJavaScriptEnabled(true);
webSettings = contentWeb.getSettings();
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setJavaScriptEnabled(false);
String baseUrl = "http://m.fanai.com";
// contentWeb.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null);
String css = "<style type=\"text/css\"> img {" +
"width:100%;" +
"height:auto;" +
"}" +
"body {" +
"margin-right:15px;" +
"margin-left:15px;" +
"margin-top:15px;" +
"font-size:45px;" +
"}" +
"</style>";
html = "<html><header>" + css + "</header><body>" + html + "</body></html>";
contentWeb.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null);
总结:问题解决还得靠自己。