标签:
大致思路:通过流的形式把网页抓取下来,然后对webView进行设置。
1.对webView进行设置
web.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); // Log.e("Test", "url....=" + url); return true; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); handler.proceed(); } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING); } else { web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); }
2.抓取网页数据:
private String getHtmlData(String bodyHTML) { String head = "<head>" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " + "<style>img{max-width: 100%; width:auto; height:auto;}</style>" + "</head>"; return "<html>" + head + "<body>" + bodyHTML + "</body></html>"; } private String getHtmlString(String urlString) { try { URL url = new URL(urlString); URLConnection ucon = url.openConnection(); InputStream instr = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(instr); ByteArrayBuffer bau = new ByteArrayBuffer(500); int current = 0; while ((current = bis.read()) != -1) { bau.append((byte) current); } return EncodingUtils.getString(bau.toByteArray(), "utf-8"); } catch (Exception e) { return ""; } }
用法:
html = getHtmlData(getHtmlString(url)); web.loadData(html, "text/html; charset=UTF-8", null);//这种写法可以正确解码
解决乱码问题:
web.getSettings().setDefaultTextEncodingName("UTF-8");
设置webView和scrollView一起滚动:
<ScrollView android:layout_width="fill_parent" android:layout_height="match_parent" android:descendantFocusability="blocksDescendants" > </ScrollView>
标签:
原文地址:http://www.cnblogs.com/jiayonghua/p/5322054.html