How to detect when back button pressed in fragment android?

In fragment you should use something like this:

  @Override
    //Pressed return button - returns to the results menu
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                 //your code

                   return true;
                }
                return false;
            }
        });
    }

In main activity you need to override the following function

@Override
public void onBackPressed()
{
     // code here to check what fragment you are on and handle that accordingly
     super.onBackPressed();  // this exits the app.
}

Documentation is available here: https://developer.android.com/reference/android/app/Activity.html#onBackPressed()


In your MainActivity

@Override
public void onBackPressed()
{
    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();
}