androidkeyboardaccessibilityandroid-jetpack-compose

Jetpack compose handle escape or back button?


How to handle a keyboard escape button correctly inside a regular app? It should trigger a back navigation if you follow the accessibility guidelines.

In the old Android way that would be handled like this:

class MainActivity: Activity 
... 
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
            Log.d("T", "onKeyUp: KEYCODE_BACK")
            onBackPressed()
        }
        return super.onKeyUp(keyCode, event)
    }

How do you handle this in correctly in Jetpack Compose?


Solution

  • Solution

    You can use keyboards modifiers like Modifier.onKeyEvent

    Example

    For example, at the root of your application :

    
    Box(
        modifier = Modifier
            .onKeyEvent {
                if(it.key == Key.Escape) {
                    // Assuming you are using jetpack compose navigation
                    navController.popBackStack()
                }
                true
            }
    ) {
        // Your content
    }