when user navigates in an application android maintains back stack of destinations . This allows android to go back to previous destination when user clicks back button . some times we need to implement our own back button behavior for best user experience . For example if we are in a timer based quiz application . when the user clicks on the back button if we go back to the previous destination without stopping the counter , it will crash the application . So first we need to know whether the user pressed the back button accidentally or not by using a dialogue box . If the user want to go back to previous destination we need to stop the counter and then go back to the previous destination.
We can control the back button hahavior byusing OnBackPressedDispatcher . This controls how back button events are dispatched to one or more onBackPressedCallback objects . callbacks are added using addCallback methods. exampe code is given below
We can control the back button hahavior byusing OnBackPressedDispatcher . This controls how back button events are dispatched to one or more onBackPressedCallback objects . callbacks are added using addCallback methods. exampe code is given below
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) { if(((findNavController().currentDestination?.id)==R.id.qaFragment)){ val builder = AlertDialog.Builder(context) builder.setMessage("do you want to exit ?") .setPositiveButton("yes", DialogInterface.OnClickListener { dialog, which -> couuntDown.cancel() findNavController().navigateUp() }) .setNegativeButton("no", null) builder.show() } else{ findNavController().navigateUp() } }
our application consists of many fragments , we only want to control the back button behavior of a single fragment. We find the particular fragment
if(((findNavController().currentDestination?.id)==R.id.qaFragment)){When the user click on the back Button in the qaFaragment , we show a conformation dialogue box asking "do you want to exit ?" . If the user clicks yes then we will stop the timer and go back to the previous destination.
you can download the full source code of this app from my Github
Comments
Post a Comment