Member-only story
Back Press Handling in Android Jetpack Compose
Create a handler function to customize your back press events
One of the significant differences that we can find in Android and iPhone is how they handle system back press. In iOS you can swipe from left to right, whereas Android offers different options. No matter which option users opt-in to use, developers can handle the event via onBackPressed
function.
History
Back in 2015 when we mostly use android activities to design a new screen, it was pretty easy to handle the system back press as we could directly override the onBackPressed
function.
Later came the fragment API. For a few years, developers struggled to handle the back press in fragments because back press event is part of an activity, not a fragment. After a while, Android team introduced onBackPressedDispatcher
which enables the fragment to add a callback where it can receive back press events.
Prerequisites
Before going any further, you must have basic knowledge of how to work with Jetpack Compose. If you’re new to Compose, I highly recommend going through the following articles:
Jetpack Compose
Jetpack Compose plays a key role in modern android development. Jetpack compose is stable and people are starting to build production-ready apps with compose. So it’s time to learn how to handle system back press in composable functions.
Out-of-the-box system back press in compose operates based on the nav controller. So when user triggers back press event, by default compose internally navigates to the previous composable function in the navigation view. To learn more about navigation in compose please read this article.
The problem comes when you want to perform a custom action on the user back press or when you want to close the bottom sheet in compose. As Jetpack compose bottom sheets are not backed by navigation library, system back press closes the current screen instead of the bottom sheet.