I am also facing the same problem where my fragment (Say Fragment A) is getting reloaded while coming back (via Device Back Button press) from other fragment (Fragment B). I have tried to find out the valid solution for this but not able to find the same. For the time being, I have done one temporary solution using Fragment lifecycle. When we popBackStack()
a fragment (Fragment B), the other fragment (Fragment A) which is coming to foreground, its onCreateView()
and onViewCreated()
will be called. So I have managed the status using this lifecycle. When first time, our Fragment A will launch, its onAttach()
function will run and in this I saved the fragment status as:
override fun onAttach(context: Context) {
super.onAttach(context)
fragmentStatus = "onAttach"
}
After in onViewCreated(), I changed this status to:
fragmentStatus = "onViewCreated"
And inside onViewCreated()
I am checking for this status value as
if (fragmentStatus == "onAttach") {
fragmentStatus = "onViewCreated"
//Write your code here for rest of the functionality
}
So now whenever this Fragment A will come into foreground, it will always found status as onViewCreated
, until this fragment get destroyed and restarted.
Note: This is a temporary solution to avoid reloading of your work inside that Fragment, but system will restart that Fragment as per its requirement.