Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView crashing on input when used with Jetpack Compose

When creating a dead-simple WebView wrapper with Jetpack Compose, the app crashes the second I enter any text. Is this a bug, or am I doing something stupid? The relevant code:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            WebViewC()
        }
    }
}

@Composable
fun WebViewC() {
    return AndroidView(viewBlock = { context ->
        WebView(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    return false
                }
            }
            loadUrl("https://google.com")
        }
    })
}

The crash:

E/MessageQueue-JNI: java.lang.IllegalStateException: KeyEvent can't be processed because this key input node is not active.
        at androidx.compose.ui.input.key.KeyInputModifier.processKeyInput(KeyInputModifier.kt:62)
        at androidx.compose.ui.platform.AndroidComposeView.sendKeyEvent(AndroidComposeView.kt:173)
        at androidx.compose.ui.platform.AndroidComposeView.dispatchKeyEvent(AndroidComposeView.kt:177)
like image 752
Gordon Fontenot Avatar asked Dec 04 '20 02:12

Gordon Fontenot


Video Answer


2 Answers

If you want to dynamic change url you need to add update method too.

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebPageScreen(urlToRender: String) {
  AndroidView(factory = {
    WebView(it).apply {
      layoutParams = ViewGroup.LayoutParams(
          ViewGroup.LayoutParams.MATCH_PARENT,
          ViewGroup.LayoutParams.MATCH_PARENT
      )
      webViewClient = WebViewClient()
      loadUrl(urlToRender)
    }
  }, update = {
    it.loadUrl(urlToRender)
  })
}
like image 104
Vova Avatar answered Oct 05 '22 20:10

Vova


It appears that this was in fact a bug in Compose. Updating to the newest version (alpha09 at the time of this answer) seems to have fixed the issue for me.

like image 22
Gordon Fontenot Avatar answered Oct 05 '22 21:10

Gordon Fontenot