Skip to content

Instantly share code, notes, and snippets.

@manishkpr
Last active May 17, 2020 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save manishkpr/e8132a80ba64806173d004bb36045b6f to your computer and use it in GitHub Desktop.
Save manishkpr/e8132a80ba64806173d004bb36045b6f to your computer and use it in GitHub Desktop.
Android - handle back press in Fragment More Details Visit: http://manishkpr.webheavens.com
This article describes how our FragmentBack works under the hood.
BaseFragment
First step to create back-sensitive fragments is to define 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 base class, but you can define it via 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 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 new back-press event. Notified fragment can indicate event consumption by returning true, in this case we stop iterating and leave the method. If no fragment consumeed 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<Fragment> 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
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() {
Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
return true;
}
}
We are done!
@binrebin
Copy link

binrebin commented May 17, 2020

How about this implementaion with Dagger.
that s DaggerFragment and DaggerAppCompatActivity ..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment