Haroun Hajem
Haroun Hajem

Reputation: 5628

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?

Upvotes: 1

Views: 2793

Answers (2)

asem elkhouli
asem elkhouli

Reputation: 29

in MainActivity

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
            onBackPressedDispatcher.onBackPressed()
            //Your code
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //Your code
        }
        return super.onKeyUp(keyCode, event)
    }

You can write a custom method in

 private val mainViewModel: MainViewModel by viewModels()

and call it in //your code for example i use it to hide bottom bar or show it again

 mainViewModel.changeIsBottomBarVisible(true)

Upvotes: 0

Jolan DAUMAS
Jolan DAUMAS

Reputation: 1374

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
}

Upvotes: 0

Related Questions