开发过程中或多或少有一些极端情况,比如这次有用户说他是安卓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);
}
}