[android] How to implement onBackPressed() in Fragments?

Easy way to handle onBackPressed() in Fragments

Step 1: Create a static boolean in activity.

public static Fragment_one;

Step 2: On MainActivity(Activity that holds fragment) in On Create method, declare

Fragment_one=true;

Step 3: Override onBackPressed() in MainActivity

@Override
public void onBackPressed() {

    if(Fragment_one) {
     //Back key pressed on fragment one

    }else {
      //Back key pressed on fragment two
    }
}

Step 4: On fragment_one onCreateView method declare

MainActivity.Fragment_one=true;

Step 5 On fragment_two onCreateView method declare

MainActivity.Fragment_one=false;

Note: This method can be only applicable to TWO fragments.