Skip to content
This repository was archived by the owner on Jul 9, 2019. It is now read-only.

Handling onBackPressed event

bkolarov-appolica edited this page Apr 11, 2017 · 1 revision

Suppose you have the FragmentController and you want its children to be able to receive the Activity onBackPressed event. Luckily for you we implemented a simple chain of responsibility pattern for passing this event. Here is what you need to do:

First you have to pass the back pressed event to FragmentController by calling FragmentController#onBackPressed(). This may be from wherever you receive it.

Then you must implement OnBackPressedListener in FragmentController's children fragments.

OnBackPressedListener

  • boolean onBackPressed() - Called when an onBackPressed event was received. Return true if the event was handled, false if not and you want to pass it up in the chain.

When FragmentController receives the back pressed event, it will get the currently visible fragment and will try to pass the event to it. If the child fragment doesn't handle the event, FragmentController will try to pop an entry from the back stack. If nothing was popped, this will be concidered as the event was not handled by any fragment and FragmentController#onBackPressed() will return false. If the event was handled by the child fragment or the controller itself, it will return true.

Have in mind that FragmentController#onBackPressed() is actually an implementation of OnBackPressedListener's boolean onBackPressed() method, so if you nest a FragmentController inside another controller, the chain will work.

Examples

In activity:

...
@Override
public void onBackPressed() {
    final FragmentController fragmentController =
            (FragmentController) getSupportFragmentManager().findFragmentByTag(CONTROLLER_TAG);

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

In a child fragment of FragmentController:

...
@Override
public boolean onBackPressed() {
    final boolean popped = FragmentUtil.getFragmentController(this).pop(true);
    return popped;
}
...
Clone this wiki locally