WebView 加载html

2019-04-19  本文已影响0人  胡洁_ec66

WebView是我们项目中经常用到的,用来展示一些信息。一般情况,都是后台直接返回一个url我们直接加载就可以了。
有朋友向我吐槽,他们的后台直接返回html,还需要处理图片显示的问题。
下面我就把WebView加载html片段做一下简单的记录。

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:src="@mipmap/back" />
    </RelativeLayout>

    <com.landain.tttest.CustomScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingLeft="16dp"
            android:paddingRight="16dp">

            <TextView
                android:id="@+id/news_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:lineSpacingExtra="20dp"
                android:text="重要讲话"
                android:textSize="18sp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/news_status"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="前线网"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/news_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:text="2019-04-08"
                    android:textSize="12sp" />
            </LinearLayout>

            <WebView
                android:id="@+id/news_webView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="26dp" />

        </LinearLayout>
    </com.landain.tttest.CustomScrollView>
</LinearLayout>

布局文件比较简单,一个ScrollView嵌套了一个WebView。当然我们用了自定义的ScrollView主要是为了解决滑动冲突的问题。

loadData()和loadDataWithBaseUrl()加载html片段

public void loadData(String data, String mimeType, String encoding)

public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)

loadDataWithBaseURL()比loadData()多两个参数,可以指定HTML代码片段中相关资源的相对根路径,也可以指定历史Url,两个方法的其余三个参数相同。
两种都可以用来显示html标签,但是loadData()会出现网页加载不完美,图片加载不出来等情况。因为loadData()中的html data中不能包含'#', '%', '', '?'四中特殊字符,出现这种字符就会出现解析错误。所以使用loadDataWithBaseURL()来加载就可以了。

图片宽度超过屏幕

html中有些图片尺寸是不固定的,造成宽度超过了屏幕。
解决方案就是方法把 img 标签width全部替换为100%

mWebView.getSettings().setJavaScriptEnabled(true);
String varjs = "<script type='text/javascript'> \nwindow.onload = function()\n{var $img = document.getElementsByTagName('img');" +
                "for(var p in  $img){$img[p].style.width = '100%'; $img[p].style.height ='auto'}}</script>";//将img标签属性定死的js代码
data = data.replaceAll("width=\"\\d+\"", "width=\"100%\"").replaceAll("height=\"\\d+\"", "height=\"auto\"");
mWebView.loadDataWithBaseURL(null,data, "text/html", "utf-8", null);
//mWebView.loadDataWithBaseURL(null,varjs+data, "text/html", "utf-8", null);//img标签属性定死执行的加载代码

如果hmtl标签中图像没用定义宽高,使用默认尺寸的话,要适应屏幕就需要使用js代码将img标签属性定死。

点击查看大图

思路是加载网页时获取到图片,给图片设置点击事件,传入到图片浏览界面。详细查看上一篇博客

WebView 点击查看大图https://www.jianshu.com/p/3f33d3458c76

上边提到ScrollView嵌套WebView造成滑动冲突问题

-------通过自定义ScrollView解决滑动冲突

代码如下:

public class CustomScrollView extends ScrollView{
    private GestureDetector mGestureDetector;
    OnTouchListener mGestureListener;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // 如果水平滑动返回false
    class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if(Math.abs(distanceY) > Math.abs(distanceX)) {
                return true;
            }
            return false;
        }
    }
}

如果图片链接是https开头造成图片不显示

解决方案

在webview加载页面之前,设置加载模式为:

MIXED_CONTENT_ALWAYS_ALLOW//(不太安全),
//或者
MIXED_CONTENT_COMPATIBILITY_MODE//(个人建议)。
//另外在webview设置中还可以加上另外一个设置:
websettings.setBlockNetworkImage(false);

加上混合内容模式设置,代码如下:

websettings.setBlockNetworkImage(false);//不阻塞网络图片
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    //允许混合(http,https)
    //websettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    websettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}

通过上面的设置,发现有些图片仍然不能显示。又经过多方搜索,发现了其他问题。
图片不显示原因还有可能是证书问题。
既然用到了https,我们大部分时候都是为了网络安全问题,如果想要更好的方案,可以参考https://www.jianshu.com/p/56e2b0bf9ab2

如果我们不考虑证书安全,则可以直接这样写。

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed();//接受所有网站的证书
    }
});

希望对大家有所帮助!!!

上一篇 下一篇

猜你喜欢

热点阅读