Something strange happened while I was starting up a new project. Eveything was working great until I created a new Android Fragment. At first it all seemed okay but as I moved my eyes around I saw that
strike through. It could only mean one thing and that is deprecation. And there it was our beloved one in Android fragment onActivityCreated() is deprecated.
Let us first see what has the statement has to say as it is in the image below
Now what does that mean in simple words ? Let me break the decision down for you and answer. Why Android fragment onActivityCreated() is deprecated ?
The written statement explains why did the onActivityCreated() exist in the first place ? Well, it did because the fragments just cannot be created independently. They must be hosted on an Activity.
And the fragment had to somehow know when the activity was created. Hence, the need for such thing lead to development of onActivityCreated().
If that was a requirement back then why deprecate now ? A really good question, that I myself thought. And, here’s what I found out.
Need for onActivityCreated() deprecation
As technology and our knowledge evolve we learn and recognize the patterns and anti-patterns in development. Which must be the case the ways of yesterday may not hold true for tomorrow.
In such similar fashion developers saw the tight coupling of code dependent to the Activity’s life cycle. And they decided that it is not a good practice anymore to be dependent on the activity attach to do certain things inside the fragment.
Most importantly, the clean architecture and inversion of control principle takes its tool on the decision. It is mentioned all the external parameters should be passed in the form of a dependency.
That being said, you should do all your view related initialization in onViewCreated(). And if something else comes up such as mimicking the same behavior as onActivityCreated I quote:
“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.”
If you want to read the actual text and see code changes you can read more.