WebView Crash on Android 5-5.1 (API 21-22) Resources$NotFoundException: String resource ID #0x2040002

前端 未结 4 1863
难免孤独
难免孤独 2021-02-01 01:49

I am in the process of updating an Android app from API 27 to API 29 and I noticed that I get a crash when trying to render a WebView on an emulator based on 5.0 and/or 5.1. Thi

4条回答
  •  死守一世寂寞
    2021-02-01 01:54

    It seems to be a bug with appcompat 1.1.0 - https://issuetracker.google.com/issues/141132133

    While you can try downgrading appcompat or wait for a fix, you can also try

    Using a custom WebView:

    private fun Context.getLollipopFixWebView(): Context {
        return if (Build.VERSION.SDK_INT in 21..22) {
            createConfigurationContext(Configuration())
        } else this
    }
    
    /**
     * Workaround appcompat-1.1.0 bug https://issuetracker.google.com/issues/141132133
     */
    class LollipopFixWebView(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
        WebView(context.getLollipopFixWebView(), attrs, defStyle)
    

    Or adding this workaround to the parent Activity of your WebView:

        // Workaround appcompat-1.1.0 bug https://issuetracker.google.com/issues/141132133
        override fun applyOverrideConfiguration(overrideConfiguration: Configuration) {
            if (Build.VERSION.SDK_INT in 21..22) {
                return
            }
            super.applyOverrideConfiguration(overrideConfiguration)
        }
    

    Credits and kudos to https://github.com/ankidroid/Anki-Android/issues/5507 There the guy believes it's happening to Android 7 as well but I couldn't replicate

    Updates

    The custom WebView solution may introduce a new problem: keyboard not showing for all Android versions.

    So we'll need to set isFocusable and isFocusableInTouchMode to the custom WebView class prevent such problem

    class LollipopFixWebView : WebView {
        constructor(context: Context) : this(context, null)
        constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context.getLollipopFixWebView(), attrs, defStyleAttr) {
            isFocusable = true
            isFocusableInTouchMode = true
        }
    }
    

    Disclaimers

    My minSdk version is 21 (Lollipop) so can't guarantee my solution works for apps with lower minSdk version

提交回复
热议问题