码迷,mamicode.com
首页 > Web开发 > 详细

WebView自适应并嵌套在ScrollView里

时间:2016-03-26 10:55:13      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

大致思路:通过流的形式把网页抓取下来,然后对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>

 

WebView自适应并嵌套在ScrollView里

标签:

原文地址:http://www.cnblogs.com/jiayonghua/p/5322054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!