美文网首页
自定义WebView注意事项!!!

自定义WebView注意事项!!!

作者: 王家匀匀 | 来源:发表于2021-03-22 17:16 被阅读0次

典型的错误写法:

 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;
    }

相关文章

网友评论

      本文标题:自定义WebView注意事项!!!

      本文链接:https://www.haomeiwen.com/subject/jztthltx.html