How to implement onBackPressed() in Fragments?

Android_programmer_camera picture Android_programmer_camera · Mar 27, 2011 · Viewed 495.2k times · Source

Is there a way in which we can implement onBackPressed() in Android Fragment similar to the way in which we implement in Android Activity?

As the Fragment lifecycle do not have onBackPressed(). Is there any other alternative method to over ride onBackPressed() in Android 3.0 fragments?

Answer

Hw.Master picture Hw.Master · Jul 22, 2014

I solved in this way override onBackPressed in the Activity. All the FragmentTransaction are addToBackStack before commit:

@Override
public void onBackPressed() {

    int count = getSupportFragmentManager().getBackStackEntryCount();

    if (count == 0) {
        super.onBackPressed();
        //additional code
    } else {
        getSupportFragmentManager().popBackStack();
    }

}