Is there a way in which we can implement onBackPressed()
in Android Fragment similar to the way in which we implement in Android Activity?
As the Fragment lifecycle do not have onBackPressed()
. Is there any other alternative method to over ride onBackPressed()
in Android 3.0 fragments?
This worked for me: https://stackoverflow.com/a/27145007/3934111
The solution is simple:
1) If you have a base fragment class that all fragments extend, then add this code to it's class, otherwise create such a base fragment class
2) In your Activity class, override onBackPressed as follows:
3) In Your Fragment class, add your desired code:
According to @HaMMeRed answer here is pseudocode how should it works. Lets say that your main activity is called
BaseActivity
which has child fragments (like in SlidingMenu lib example). Here are the steps:First we need create interface and class which implements its interface to have generic method
Create class interface
OnBackPressedListener
Create class which implements skills of
OnBackPressedListener
Since now, we will work on our code
BaseActivity
and its fragmentsCreate private listener on top of your class
BaseActivity
create method to set listener in
BaseActivity
in override
onBackPressed
implement something like thatin your fragment in
onCreateView
you should add our listenerVoila, now when you click back in fragment you should catch your custom on back method.
Best solution,
You should add interface to your project like below;
And then, you should implement this interface on your fragment;
And you can trigger this onBackPressed event under your activities onBackPressed event like below;
According to the AndroidX release notes,
androidx.activity 1.0.0-alpha01
is released and introducesComponentActivity
, a new base class of the existingFragmentActivity
andAppCompatActivity
. And this release brings us a new feature:You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed()
callbacks without needing to override the method in your activity.