4

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?

S.R
  • 2,819
  • 2
  • 22
  • 49
I DAE
  • 113
  • 2
  • 2
  • 7

3 Answers3

1

You need to override onBackPressed() in your Activity.

 @Override
    public void onBackPressed() {
    YourFragment mYourFragment = (YourFragment)getFragmentManager().findFragmentByTag(YourFragment.TAG);
    if(mYourFragment!=null){
    // Your Code
  }
Jaydeep Patel
  • 146
  • 2
  • 9
  • i try,I want to click back button to back activity from fragment, i .`addToBackStack()` then pop when i click,but not work – I DAE Aug 19 '15 at 09:39
0

Just override onBackButton() in your Activity. Detect if the Fragment is currently shown and detach it from your Activity. I think you can get the fragment by tag, or something like that.

StG
  • 257
  • 2
  • 11
  • I want to click back button to back activity from fragment, i .`addToBackStack()` then pop when i click,but not work – I DAE Aug 19 '15 at 09:39
  • Use FragmentManager.beginTransaction.remove(Fragment) instead. Note that this is NOT the correct syntax to invoke the method. – StG Aug 19 '15 at 10:02
0

Fragment is a part of activity, just handle the back key in activity, manage your fragments in activity should be ok.

T-Chen
  • 173
  • 6
  • I want to click back button to back activity from fragment, i .`addToBackStack()` then pop when i click,but not work – I DAE Aug 19 '15 at 09:39