admin管理员组

文章数量:1123602

I want to intercept all KeyEvents in Activity regardless of focus.

Minimal working example:

class MainActivity : ComponentActivity() {
    @SuppressLint("RestrictedApi")
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        Log.d(TAG, "$event")
        return super.dispatchKeyEvent(event)
    }
}

Start the activity by pressing on the app icon, press a hardware key (e.g., keyboard arrow if using an emulator). I expect 2 KeyEvents: ACTION_DOWN followed by ACTION_UP. This is exactly what we get:

App: ACTION_DOWN
App: ACTION_UP

Now, as soon as we add something on the screen in Compose, we are missing very first ACTION_DOWN event:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Text("Hello, world!")
        }
    }
    /* rest is the same */
}

What we get is this:

Compose Focus: Owner FocusChanged(true)
App: ACTION_UP

Subsequent keystrokes work:

Compose Focus: Owner FocusChanged(true)
App: ACTION_UP
App: ACTION_DOWN
App: ACTION_UP

How do we avoid first event being consumed by Compose world? I have tried using FocusRequester to no avail.

本文标签: androidMissing first KeyEvent when using ComponentActivitysetContent()Stack Overflow