How to override onBackPressed() in Fragment

I DAE picture I DAE · Aug 19, 2015 · Viewed 11k times · Source

I want to use onBackPressed() in Fragment to back to its Activity when I click the back button, but I don't know how to do it. I can't override onBackPressed() in Fragment, because there isn't this methods. Can anyone help me?

Answer

Jaydeep Patel picture Jaydeep Patel · Aug 19, 2015

You need to override onBackPressed() in your Activity.

 @Override
    public void onBackPressed() {
    YourFragment mYourFragment = (YourFragment)getFragmentManager().findFragmentByTag(YourFragment.TAG);
    if(mYourFragment!=null){
    // Your Code
  }