onActivityCreated is deprecated, how to properly use LifecycleObserver?

As per the changelog here

The onActivityCreated() method is now deprecated. Code touching the
fragment’s view should be done in onViewCreated() (which is called
immediately before onActivityCreated()) and other initialization code
should be in onCreate(). To receive a callback specifically when the
activity’s onCreate() is complete, a LifeCycleObserver should be
registered on the activity’s Lifecycle in onAttach(), and removed once
the onCreate() callback is received.

You can do something like this in your fragment class:

class MyFragment : Fragment(), LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreated() {
        // ... Your Logic goes here ...
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        activity?.lifecycle?.addObserver(this)
    }

    override fun onDetach() {
        activity?.lifecycle?.removeObserver(this)
        super.onDetach()
    }
}

Leave a Comment