出现这个问题肯定是使用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)
}