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 is my solution:
If you wanted that sort of functionality you would need to override it in your activity, and then add a
YourBackPressed
interface to all your fragments, which you call on the relevant fragment whenever the back button is pressed.Edit: I'd like to append my previous answer.
If I were to do this today, I'd use a broadcast, or possibly a ordered broadcast if I expected other panels to update in unison to the master/main content panel.
LocalBroadcastManager
in the Support Library can help with this, and you just send the broadcast inonBackPressed
and subscribe in your fragments that care. I think that Messaging is a more decoupled implementation and would scale better, so it would be my official implementation recommendation now. Just use theIntent
's action as a filter for your message. send your newly createdACTION_BACK_PRESSED
, send it from your activity and listen for it in the relevant fragments.Do not implement ft.addToBackStack() method so that when you pressed back button your activity will be finished.
Very short and sweet answer:
Explanation of whole scenario of my case:
I have FragmentA in MainActivity, I am opening FragmentB from FragmentA (FragmentB is child or nested fragment of FragmentA)
Now if you want to go to FragmentA from FragmentB you can simply put
getActivity().onBackPressed();
in FragmentB.In activity life cycle, always android back button deals with FragmentManager transactions when we used FragmentActivity or AppCompatActivity.
To handle the backstack we don't need to handle its backstack count or tag anything but we should keep focus while adding or replacing a fragment. Please find the following snippets to handle the back button cases,
Here, I won't add back stack for my home fragment because it's home page of my application. If add addToBackStack to HomeFragment then app will wait to remove all the frament in acitivity then we'll get blank screen so I'm keeping the following condition,
Now, you can see the previously added fragment on acitvity and app will exit when reaching HomeFragment. you can also look on the following snippets.