Android – handle back press in Fragment

22. 12. 2023

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

Do you want more?

We share the world of software development on our Instagram. Join us 🙂

minimum viable product from skoumal instagram

 

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: [email protected].

10 Entrepreneurship Lessons Worth Thousands of Dollars

Instead of great success we have experienced great entrepreneurship lessons (for now). It also transformed me, a person who has …

Read article

Unique Czech words reflecting coronavirus now also with English explanations as Flashcard quiz in Vocabulary Miner

  Project ÄŚestina 2.0 covering a variety of the modern Czech language with its slangs and new words has joined …

Read article

Performance of built-in higher-order functions Map, Filter, Reduce, and flatMap vs. for-in loop in Swift

  The most popular higher-order functions are map, filter, and reduce. We all use them since we think that syntax …

Read article

Contact