Skip to main content

Controlling Back button Behavior in Fragment-- kotlin

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

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

Popular posts

Simple Calculator in Android

You can view new updated simple calculator with ViemModel and LiveData in my new blog    https://androidtuts4u.blogspot.com/2021/10/simple-calculator-with-viewmodel-and.html To create a calculator first  we need to create the layout of the calculator. Layout  is created  using XML file given below <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent" >  <EditText     android:id="@+id/result_id"       android:layout_width="fill_parent"     android:layout_height="120dp"   />  <Button    android:id="@+id/Btn7_id"      android:layout_width="70dp"    android:layout_height="60dp"    android:layout_below="@id/result_id"   ...

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path....

Android Sqlite and ListView Example

This is simple application which insert data into Sqlite database --and shows the data  from the database in a ListView ListView is not used in android Anymore . We use RecyclerView and CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with CardView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html This  is the first Activity of application which shows data from database in listview. Register here buton will start a Registration Activity. Submit button will add data to database and show it in the ListView of MainActivity. Update can be performed by clicking ListView items.     you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdS0dtT1R2TXdBWEE&usp=sharing click on the abov...