Android 5.x 版本中 WebView 出现 Error inflating class android.webkit.WebView 的解决方法

在 Android 5.x 版本中使用WebView可能会报如下的错误

android.view.InflateException: Binary XML file line #24: Error inflating class android.webkit.WebView

解决方案1:

使用 createConfigurationContext() 方法去获取 Context

public class LollipopFixedWebView extends WebView {

    public LollipopFixedWebView(Context context) {
        super(getFixedContext(context));
    }

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

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

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public LollipopFixedWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(getFixedContext(context), attrs, defStyleAttr, defStyleRes);
    }

    public LollipopFixedWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing) {
        super(getFixedContext(context), attrs, defStyleAttr, privateBrowsing);
    }

    public static Context getFixedContext(Context context) {
        // Android Lollipop 5.0 & 5.1
        if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT <= 22) 
            return context.createConfigurationContext(new Configuration());
        return context;
    }
}

解决方案2:

在项目的 build.gradle 中,appcompat 为1.1.0的版本可能存在bug,使用如下版本可解决问题

implementation 'androidx.appcompat:appcompat:1.2.0'

 

你可能感兴趣的:(android,webview,java,安卓,gradle)