Android - handle back press in Fragment



Last Updated on

This article describes how our FragmentBack works under the hood. If you are looking for ready to use solution than it is much better to use this tiny (1.5 kB) library instead of doing it yourself. In addition to the functionality described here, in FragmentBack library, you can also define a priority for your fragments.

green fragments

BaseFragment

The first step to create back-sensitive fragments is to define the interface that we can call to notify particular fragments about back-press. It contains only one method onBackPressed() which returns a value that indicates if back-press event was consumed by the fragment.

In this example, we use the base class, but you can define it via the interface as well.

public class BaseFragment extends Fragment {
   /**
    * Could handle back press.
    * @return true if back press was handled
    */
   public boolean onBackPressed() {
       return false;
   }
}

BaseActivity

The next step is an activity with the overwritten Activity.onBackPressed() method. In its body, we list all fragments attached to activity and for this implementing our BaseFragment class/interface we notify them about the new back-press event. The notified fragment can indicate event consumption by returning true, in this case, we stop iterating and leave the method. If no fragment consumed the event we invoke standard Activity.onBackPressed() implementation to dismiss activity.

Now simply by extending this BaseActivity all back-press events will be propagated to all your BaseFragments placed in it.

public class BaseActivity extends Activity {

   @Override
   public void onBackPressed() {

           List fragmentList = getSupportFragmentManager().getFragments();

           boolean handled = false;
           for(Fragment f : fragmentList) {
               if(f instanceof BaseFragment) {
                   handled = ((BaseFragment)f).onBackPressed();

                   if(handled) {
                       break;
                   }
               }
           }

           if(!handled) {
               super.onBackPressed();
           }
   }

}

MyFragment

The last step is to implement such back-sensitive fragment. There is nothing simpler, just extend/implement your BaseFragment class/interface and handle back-press events in onBackPressed() properly or just return false to ignore it.

public class MyFragment extends BaseFragment {

      /**
      * Back pressed send from activity.
      *
      * @return if event is consumed, it will return true.
      */
      @Override
      public boolean onBackPressed() {
        if (openedLine < 0) {
            return false;
        } else {
            closeDetail();
            return true;
            }
      }
}

We are done!

Do you need more detailed help? Book a consultation:
Let’s chat about it

 

If you are into Android, do not hesitate and let us know your opinion in the comment section below. We also tend to look for Android dev (iOS as well), but there are also chances for a project manager or a tester. Send us an e-mail: skoumal@skoumal.net.

Vladislav Skoumal
SKOUMAL CEO

Comments

Author picture

This implementation will work most of the times, but sometimes will behave wrongly:

1) because FragmentManager#getFragments() returns the fragments in order as they were added, first fragment will handle onBackPressed() — the last fragment should probably handle it instead (which means you should iterate the collection backwards)

2) if it’s used in ViewPager, first fragment added to ViewPager will be handling the onBackPressed() — in this case you may use Fragment#getUserVisibleHint() to check if a fragment is visible to user and if it should handle the onBackPressed()

But otherwise good job 🙂

Reply
Author picture

Thanks it working well

Reply
Load more
Leave a comment

  Project Čestina 2.0 covering a variety of the modern Czech language with its slangs and new words has joined forces with vocabulary Flashcard app Vocabulary Miner. They are bringing new words not only to Czechs but ...

Read post

  The most popular higher-order functions are map, filter, and reduce. We all use them since we think that syntax is much better and it is even faster to write them than the old way for-in loop. But is it really true ...

Read post

In order to allow our CI server to deploy applications on Google Play automatically, we have to generate the JSON key. Thanks to this key, we can quickly deploy applications without manually uploading each and every version. We can also control what version we did upload on Google Play through our ...

Read post

The Czech vocabulary-building app Vocabulary Miner created by studio SKOUMAL is based on the popular Flashcard System and special algorithm.  It promises the user to simply say more with every word and delivers it through effective, yet simple vocabulary training by ...

Read post