In recent google changes for android, version 1.3.0 of Fragment has also added a new FragmentOnAttachListener interface to replace the less-flexible onAttachFragment method. As in document mentioned:
This method is deprecated. The responsibility for listening for fragments being attached has been moved to FragmentManager. You can add a listener to this Activity's FragmentManager by calling FragmentManager.addFragmentOnAttachListener(FragmentOnAttachListener) in your constructor to get callbacks when a fragment is attached directly to the activity's FragmentManager.
So I implement this listener in onCreate() method of BaseActivity class that all my activities extends from it:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = getViewBinding()
setContentView(_binding!!.root)
val fm = supportFragmentManager
val listener = FragmentOnAttachListener {
fragmentManager, fragment ->
// Respond to the fragment being attached.
}
fm.addFragmentOnAttachListener(listener)
}
Source document explains:
Listener for receiving a callback immediately following Fragment.onAttach(Context). This can be used to perform any additional setup / provide any dependencies that the Fragment may need prior to child fragments being attached or the Fragment going through Fragment.onCreate(Bundle). Called after the fragment has been attached to its host. This is called immediately after Fragment.onAttach(Context) and before Fragment.onAttach(Context) has been called on any child fragments.
In MainActivity I have ButtomNavigationView setup with navigation component. The problem is when application runs for first time that fragments onAttach() called, this listener receive callback immediately before onAttach(), but in next time when onAttach() called manually, listener doesn't receive callback. To be clear, I have a button in one of my fragment that in its click event, fragment be refreshed and so onAttach() called again. When this happen, FragmentOnAttachListener doesn't work. Can anyone help me why listener doesn't receive callback again? Thanks in advance.