My MainActivity on start opens SignInFragment, SignIn after succesful auth opens MainFragment. How can I close MainActivity from these two fragments on back pressed? When I tried to add back pressed callback into needed Fragment, it’s closing MainActivity from every fragment, instead of only that one. As well I can’t use popBackStack, since Activity isn’t in BackStack. Is there’s correct sollution to close Activity from needed fragment on back pressed?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
There are fews ways to close the activity at onBack pressed, as you are more related to fragment. Firstly create an interface named OnBackPressed and the interface contains the function onBackPressed (any name you would prefer). Implement the interface in the fragments, as it’s function onBackPressed will be defined there, so place activity?.onFinish() in the body of the function.
First of all, at the MainActivity you override the onBackPress function, and than place the check(if condition).
This is one of the way you can close the activity when the back button is tapped in the fragment’s.
Sorry for the late replay, Please Use Below code for best practice :
Just put this code on oncreateView or onViewCreated
when you click back button, this code will close your parent activity.