Android - handle back press in Fragment

20.10.2016

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!

 

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

[caption id="attachment_2730" align="aligncenter" width="1024"] Photo by Farzad Nazifi on Unsplash[/caption]   Every Android app has its unique identifier called applicationId and you have to choose it wisely because it cannot be changed later. Here are two main reasons ...

Read post

  Twitter is there to enhance your Android skills. How? Just follow the right people and get your feed updated with Android insights and hacks. If you are from the Czech Republic or Slovakia, you can be surely inspired by your local Slovak and Czech ...

Read post

  Twitter can definitely educate the Android Developer you are. It is as easy as to follow the right people and then just checking their regular insights in your feed.  The only thing that remains is how to choose the right people.  And we can try to help you with ...

Read post

The Flashcard maker app Vocabulary Miner by Czech SKOUMAL Studio helps memorize vocabulary that the user really needs. Now, topical Word lists tailored to the needs of expats and travelers are available in 12 languages. Users can effectively learn Czech ...

Read post