Android - handle back press in Fragment

20.10.2016

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

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

Have you ever felt like Google Play is discriminating your app by rating in a long run? You are not alone. What is the real problem here? Google Play was re-branded from Google Market a few years back after it reached its full model capacity. Many features have been redone, removed ...

Read post

We, SKOUMAL Studio, develop mobile apps. We are strong believers in freedom, yet reliability, flat hierarchy yet careful attitude, and no rigidity, yet without anarchy. Our own product - language app Vocabulary Miner - needs to speak more languages to our students. That will be your job ...

Read post

All things considering you are probably using git to version your changes, if not here is a quick-start guide. You see I am a bit punctual towards my code and documenting its changes, I write extensive commit messages however I'm extremely reluctant to write changelogs for clients or users ...

Read post