I have a Fragment A in My app.
From the Fragment A, I am moving to Fragment B.
Note that I am adding the Fragment B on Fragment A (not replacing the Fragment.)
Now, When I coming back to Fragment A from Fragment B, I have to call a method of Fragment A and that's Why I am calling that method in life cycle method of Fragment A : in onResume(), onViewCreated()
But What I noticed by putting log in both the method that these methods are not calling means I am not getting Log in logcat and the method which I have called in these two methods is not executing.
What might be the issue? Thanks.
I am doing as below for your reference:
override fun onResume() {
super.onResume()
Log.e("onResume 1","onResume 1")
(activity as HomeActivity).updateToolbar(false)
setLanguageSpecificData()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.e("onViewCreated","onViewCreated")
setLanguageSpecificData()
}
CodePudding user response:
Problem:
The way you mentioned in your question that:
I am adding the Fragment B on Fragment A (not replacing the Fragment.)
So, There is a difference between what lifecycle methods gets called based on replace
& add
.
If you take a look at this answer :https://stackoverflow.com/a/21684520/9715339
In terms of fragment's life cycle events
onPause
,onResume
,onCreateView
and other life cycle events will be invoked in case ofreplace
but they wont be invoked in case ofadd
Also, It's tied to activity lifecycle as well.
Solution:
Looking at your code you want to update something when current visible fragment changes or in other words backstack
changes.
For that you can do this in your activity:
supportFragmentManager.addOnBackStackChangedListener {
//when backstack changes get the current fragment & do something with that info
val frg = supportFragmentManager.findFragmentById(R.id.root_container)
if (frg is AFragment){
// do something like updateToolbar(false)
} else if (frg is BFragment){
//something else
}
Log.d("FrgTest-",frg.toString())
}
In fragment you can do requireActivity().supportFragmentManager
& rest will be fine.
Read:
This is just an example for backstack change. If you want to communicate between fragments you can use other ways like setFragmentResultListener
as well.
This may help: https://developer.android.com/guide/fragments/communicate#kotlin