« Migrate The Deprecated OnBackPressed Function — Android 13
While Targeting Android 13 , OnbackPressed
Override Function is deprecated😢. Usually, we used to intercept on backpress and add animations. we all know, this onBackPressed function will call as soon as the Back button is clicked (Hardware) or back pressed from the navigation gesture. But, now it’s time to change
Now, its time to Migrate.. 🤞 Let’s see our old way of usage,
1override fun onBackPressed() {2 //showing dialog and then closing the application..3 showDialog()4 }56 private fun showDialog(){7 MaterialAlertDialogBuilder(this).apply {8 setTitle("are you sure?")9 setMessage("want to close the application ?")10 setPositiveButton("Yes") { _, _ -> finish() }11 setNegativeButton("No", null)12 show()13 }14 }
Step 1 :
To enable the predictive back gesture APIs, set enableOnBackInvokedCallback to true in the manifest.
1<application2 ...3 android:enableOnBackInvokedCallback="true" // Enables this feature.4 ... >5...6</application>
STEP 2 :
Add the callback in the onBackPressedDispatcher(). This should be inside the onCreate function and it’s a good practice to use the bottom of setContentView or after Binding the layout.
1override fun onCreate(savedInstanceState: Bundle?) {2 super.onCreate(savedInstanceState)3 setContentView(R.layout.activity_main)4 // adding onbackpressed callback listener.5 onBackPressedDispatcher.addCallback(this,onBackPressedCallback)6}
Final MainActivity code :
1class MainActivity : AppCompatActivity() {23 private val onBackPressedCallback = object : OnBackPressedCallback(true) {4 override fun handleOnBackPressed() {5 //showing dialog and then closing the application..6 showDialog()7 }8 }910 override fun onCreate(savedInstanceState: Bundle?) {11 super.onCreate(savedInstanceState)12 setContentView(R.layout.activity_main)13 // adding onbackpressed callback listener.14 onBackPressedDispatcher.addCallback(this,onBackPressedCallback)15 }1617 private fun showDialog(){18 MaterialAlertDialogBuilder(this).apply {19 setTitle("are you sure?")20 setMessage("want to close the application ?")21 setPositiveButton("Yes") { _, _ -> finish() }22 setNegativeButton("No", null)23 show()24 }25 }26}
Now, if you not have something like Dialog box for confirmation in onBackPressed, you can get back-to-home gesture animations
, which is in Android 13.
To test it, make onBackPressedCallback
isEnabled as false
.(This will not show Dialog popup or anything inside the callback function, typically you can add this isEnabled = false under some conditions.)
make onBackPressedCallback isEnabled as false .(Note this will not show Dialog popup.)
And then, Starting with the Android 13 final release, you should be able to enable a developer option to test the back-to-home animation
On your device, go to Settings > System > Developer options
.
Select Predictive back animations
.
Launch your updated app, and use the back gesture to see it in action.
That’s it!!