自定义WebView注意事项!!!

典型的错误写法:

 public MyWebView(Context context) {
        this(context, null);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

2个注意点:

1.自定义webview的defStyleAttr不能传0,否则会导致h5的输入法调不起来。

分析:你在xml 中引用自定义的webview,实际调用的是2个参数的构造方法,然后内部又调了3个参数的构造方法,于是defStyleAttr就变成了0.

绝大多数的控件,它们带有三个参数的构造方法第三个参数传递的确实都是 0 ,但是 Webview 不是,第三个参数传递是一个样式 com.android.internal.R.attr.webViewStyle
参考:https://www.jianshu.com/p/5f8746eaada9

修改办法:每个构造办法分别调用initViews。

2.构造方法要兼容android 5.x的context,否则对应机型会奔溃:

    /**
     * 修复android5.x上webview打开崩溃bug
     *
     * @param context
     * @return
     */
    private static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return context.createConfigurationContext(new Configuration());
        }
        return context;
    }

所以正确完整代码是:

 public MyWebView(Context context) {
        super(getFixedContext(context));
        initViews(context);
    }

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

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

    /**
     * 修复android5.x上webview打开崩溃bug
     *
     * @param context
     * @return
     */
    private static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return context.createConfigurationContext(new Configuration());
        }
        return context;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容