Android – How to implement onBackPressed() in Fragments

androidandroid-fragmentsonbackpressed

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?

Best Answer

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();
    }

}