The Fragment API has always been very difficult to use, and it’s officially acknowledged. OnActivityCreated () in fragments was deprecated a month ago

Fragment 1.3.0- Alpha02 onActivityCreated() method deprecated

Let’s look at the commit log

Just a quick translation

The original purpose of onActivityCreated() is to associate the fragment’s logic with the creation of its host activity, and we discourage this coupling

We should pass an external dependency as the FragmentFactory parameter. View-related code should be placed in onViewCreated(), and other initialization code should be done in onCreate(). To receive a callback after the activity onCreate() completes, add a LifecycleObserver for the activity Lifecycle and remove it when the Lifecycle.State#CREATED callback is received

override fun onAttach(context: Context) {
    super.onAttach(context)
    requireActivity().lifecycle.addObserver(object : DefaultLifecycleObserver {
        override fun onCreate(owner: LifecycleOwner) {
            // Do whatever you want
            owner.lifecycle.removeObserver(this)}}}Copy the code

DialogFragment

What about DialogFragment? Its onActivityCreated becomes optional

Just a quick translation

DialogFragment uses onActivityCreated() to help create a Dialog. With onActivityCreated() deprecated, we should find a better way to implement this part of logic

About the view relevant code has been transferred to the DialogFragment viewLifecycleOwnerLiveData, initialization when the dialog after other initialization logic in onGetLayoutInflater completed

We still support configuring dialogs in onActivityCreated() for custom Dialogs

End

Looking at the changes to the Jetpack Fragment, it’s not hard to see that officials are trying to “lighten the load” on the fragment, taking small, independent functions out of the fragment and reducing the coupling. We’ll cover other changes in future articles

Please leave your comments in the comments section

About me

I am Flywith24, and my blog content has been classified here. You can click Watch in the upper right corner to get updates of my articles in time, oh 😉

  • The Denver nuggets
  • Jane’s book
  • Github