-
Notifications
You must be signed in to change notification settings - Fork 1
Handling onBackPressed event
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.
-
boolean onBackPressed()
- Called when an onBackPressed event was received. Returntrue
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.
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;
}
...