Reputation: 5628
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
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
Reputation: 1374
You can use keyboards modifiers like Modifier.onKeyEvent
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