Android 5.1之前版本加载WebView崩溃和乱码,图片宽度不能填充屏幕问题

开发过程中或多或少有一些极端情况,比如这次有用户说他是安卓5.1系统,使用我们APP时发现打开WebView要么是乱码,要么崩溃,这个问题其实不是什么问题,因为在开发之初根据客户人群制定了支持安卓6.0以上版本,

但是作为一名开发者来说,

有问题就要撸,

撸到没问题,

撸到代码质量高,

撸到APK包小,

撸到用户体验好

那就来解决一下吧,创建一个原生虚拟机测试一下,emmm……确实有这个问题,于是把所有的webview都测试了一下,都有问题,找到原因了,那就开始撸吧;

首先既然自带的webview不支持5.1系统,那就自定义一个WebView继承WebView,针对SDK版本判断一下,加载不同的方法即可;

/**
 * Created by SunLion on 2020/4/26.
 * 自定义webView适配5.1版本
 */
public class CustomWebView extends WebView {
    public CustomWebView(Context context) {
        super(getFixedContext(context));
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(getFixedContext(context), attrs);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(getFixedContext(context), attrs, defStyleAttr);
    }

    public static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return context.createConfigurationContext(new Configuration());
        } else {
            return context;
        }
    }
}

编译运行,等待中,emmmmm……

还是报错,流下了不甘的泪水,继续找错,继续撸……

发现在loadUrl(xxx)方法报错,赤裸裸的报错,那就换一种方式,加载html,试一试

webView.loadDataWithBaseURL(null,dictValue,"text/html","utf-8",null);

5.1没问题了,再试试安卓高版本的测一下,没问题,搞定;

关于WebView宽度不能全屏问题,

/**
 * Created by SunLion on 2020/4/16.
 * 设置WebView宽度使用全屏
 */
public class WebViewWidthUtil {

    /**
     * 设置宽度
     * @param html    代码
     * @param webView view
     */
    public void setWidth(String html, NoScrollWebView webView) {
        //自适应屏幕
        String content = html.replace("<img", "<img height=\"auto\"; width=\"100%\"");
        webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个小狼娃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值