Android 5.0,5.1中WebView出现ResourcesNotFoundException String resource ID #0x2040003

出现这个问题肯定是使用Androidx后出现的,问题出现在 androidx.appcompat:appcompat 的依赖上

百度找了一圈答案后,总结了几个解决方法:

1.直接升级appcompat的版本,这个bug基本是出现在appcompat:1.1.0版本上,目前稳定版本是1.2.0,修改成如下

dependencies {
    def appcompat_version = "1.2.0"

    implementation "androidx.appcompat:appcompat:$appcompat_version"
    // For loading and tinting drawables on older versions of the platform
    implementation "androidx.appcompat:appcompat-resources:$appcompat_version"
}

2.怕有其他问题,不能直接修改appcompat的版本号,提供如下三个方法

  1).复写webView所在Activity的getAssets()函数

override fun getAssets(): AssetManager {
    return resources.assets
}

2).自定义WebView,修改构造函数的context

class CustomWebView(context: Context, attributeSet: AttributeSet? = null) :
    WebView(getFixedContext(context), attributeSet) {

    companion object {
        private fun getFixedContext(context: Context): Context? {
            // Android Lollipop 5.0 & 5.1
            return if (Build.VERSION.SDK_INT in 21..22) context.createConfigurationContext(
                Configuration()
            ) else context
        }
    }
    
}

3).修改webView所在Activity的manifest配置

android:configChanges="uiMode"

4).代码修改configChanges

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
        if (Build.VERSION.SDK_INT in 21..22 && (resources.configuration.uiMode ==  applicationContext.resources.configuration.uiMode)) {
                return
        }
        super.applyOverrideConfiguration(overrideConfiguration)
}
override fun applyOverrideConfiguration(overrideConfiguration: Configuration) {
        if (Build.VERSION.SDK_INT in 21..22 ) {
            overrideConfiguration.uiMode = overrideConfiguration.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()
        }
        super.applyOverrideConfiguration(overrideConfiguration)
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值