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

Android List View using Custom Adapter and SQLite

following is a simple applicaton to create ListView using  Custom adapter.screenshot of the application  is like this . 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 Example is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html The ListView below the submit button is populated using Custom Adapter.Data is stored and retrieved using SQLite databsase. you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdUXE5aTNhazludjQ&usp=sharing click on the above link ->sign into  your  google account ->add this to your google drive -> open it in google drive and download it. To create a simple application like this 1.  Create a class which extends  

Unknown filesystem grub rescue> Error ubuntu

when computer shows    Unknown filesystem grub rescue>   on starting ubuntu  do these things to recover ---. Boot  your computer on a ubuntu live-CD or live-USB ---choose option "Try ubuntu without installation" ---Install Boot Repair       -  open terminal then type             sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update -press enter then type     sudo apt-get install -y boot-repair && boot-repair   ---- if you can't install Boot Repair from repository, dowload it from official   website of Boot Repair --- After Installing open it and click the "Recommended repair" button .         this will fix your system  --- Reboot your system it will work fine if your system is not fixed after this do the following(you have to install grub)   --- If your linux partition is in sda10 sudo mount /dev/sda10 /mnt sudo mount --bind /dev /mnt/d

DataBinding - ViewBinding in Android

ViewBinding is a feature that allow you to write code more easily.  First we will s ee an App without ViewBinding then we will enable ViewBinding in the App .Screenshot of our app is , it is asimple application when we  click the Button score Will Increase You can also see this tutorial in my youtube channel you can download source code of this project from GitHub https://github.com/arunkfedex/DemoNavGraphTest Layout file is activity_main.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text1