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?
Just add
addToBackStack
while you are transitioning between your fragments like below:if you write
addToBackStack(null)
, it will handle it by itself but if you give a tag , you should handle it manually.Well I done it like this, and it work for me
Simple interface
FragmentOnBackClickInterface.java
Example implementation
MyFragment.java
then just override onBackPressed in activity
Its just simple if you have An Activity A and you make 3 fragments like B ,C and D.Now if you are in fragment B or C and
onBackPressed
you want to move on Fragment D every time .Then you have to just Override theonBackPressed()
method in main Activity A and also when you jump to any fragment then pass a TAG or name of that fragment by which you recognized that fragment in main Activity A.I am giving the example of that one by which you can easily understand that....
or if you are moving from fragment B to fragment C..and on back press you want to come on Fragment D...like below
Now you have to just override the onBackPressed() method in main activity....like below..
I had the same problem and I created a new listener for it and used in my fragments.
1 - Your activity should have a listener interface and a list of listeners in it
2 - You should implement methods for adding and removing the listeners
3 - You should override the onBackPressed method to check that any of the listeners use the back press or not
4 - Your fragment must implement the interface for back press
5 - You need to add the fragment as a listener for back press
6 - You should return true from onBackPressed if the fragment uses this back press
7 - IMPORTANT - You must remove the fragment from the list onDestroy
There is a Stack used instead of the ArrayList to be able to start from the latest fragment. There may be a problem also while adding fragments to the back stack. So you need to check that the fragment is visible or not while using back press. Otherwise one of the fragments will use the event and latest fragment will not be closed on back press.
I hope this solves the problem for everyone.
I thing the best solution is
JAVA SOLUTION
Create simple interface :
And in your Activity
Finally in your Fragment:
KOTLIN SOLUTION
1 - Create Interface
2 - Prepare your Activity
3 - Implement in your target Fragment
onBackPressed()
cause Fragment to be detach from Activity.According to @Sterling Diaz answer I think he is right. BUT some situation will be wrong. (ex. Rotate Screen)
So, I think we could detect whether
isRemoving()
to achieve goals.You can write it at
onDetach()
oronDestroyView()
. It is work.