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?
None of that is easy to implement nor will it function in an optimal way.
Fragments have a method call onDetach that will do the job.
THIS WILL DO THE JOB.
Just follow these steps:
Always while adding a fragment,
Then in the main activity, override
onBackPressed()
To handle the back button in your app,
That's it!
This is just a small code that will do the trick:
Hope it helps someone :)
I have used another approach as follows:
Runnable
that the calling fragment definesonBackPressed
is called in the controlling Activity, it pops the most recent custom back action and executes itsRunnable
. If there's nothing on the Stack, the defaultsuper.onBackPressed()
is calledThe full approach with sample code is included here as an answer to this other SO question.
public class MyActivity extends Activity {
}
in your fragment add the following, dont forget to implement mainactivity's interface.
How about using onDestroyView()?