Skip to content

Instantly share code, notes, and snippets.

@manishkpr manishkpr/BackPress.java
Last active Jun 15, 2017

Embed
What would you like to do?
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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.