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?
Asked
Active
Viewed 1.2k times
4
-
Similar post solved [here](https://stackoverflow.com/a/46425415/6831069) Enjoy – Maxime Jallu Oct 02 '17 at 22:10
3 Answers
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