Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments
UPDATE:
onActivityCreated()
is deprecated from API Level 28.
onCreate():
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
If you want to view the official Android documentation, it can be found here:
onCreate()
onCreateView()
onActivityCreated()
_
There are also some slightly different, but less developed questions/answers here on Stack Overflow:
onCreate()
vsonCreateView()
onCreateView()
vsonActivityCreated()
Android Fragment onCreateView vs. onActivityCreated
If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method as well as restoring the view state when setRetainInstance used to do so.
Also accessing the view hierarchy of the parent activity must be done in the onActivityCreated, not sooner.
Is onActivityCreated() called after onViewCreated() in a Fragment?
After some further research I think I found the answer.
onActivityCreated added in version 22.1.0 void onActivityCreated
(Bundle savedInstanceState)Called when the fragment's activity has been created and this
fragment's view hierarchy instantiated. It can be used to do final
initialization once these pieces are in place, such as retrieving
views or restoring state. It is also useful for fragments that use
setRetainInstance(boolean) to retain their instance, as this callback
tells the fragment when it is fully associated with the new activity
instance. This is called after onCreateView(LayoutInflater, ViewGroup,
Bundle) and before onViewStateRestored(Bundle).
Based on the documentation:
..fragment's view hierarchy instantiated. It can be used to do final
initialization once these pieces are in place..
The view hierarchy should be fully instantiated and therefore onActivityCreated
will be called after the completion of onViewCreated
UPDATE
Info: onActivityCreated
is now deprecated
use onViewCreated(View, Bundle) for code touching the Fragment's view
and onCreate(Bundle) for other initialization. To get a callback
specifically when a Fragment activity's Activity.onCreate(Bundle) is
called, register a androidx.lifecycle.LifecycleObserver on the
Activity's Lifecycle in onAttach(Context), removing it when it
receives the Lifecycle.State.CREATED callback.
Fragment Recyclerview onCreateView, onViewCreated or onActivityCreated?
onCreateView()
will be the best choice since you're using Fragment
. The difference is onCreateView()
is the Fragment
equivalent of onCreate()
for Activities and runs during the View
creation but onViewCreated()
runs after the View
has been created.
And onActivityCreated()
calls after onCreate()
method of the Activity
completes as you can see in here: https://stackoverflow.com/a/44582434/4409113
What is the difference between requireActivity and onActivityCreated
We should split this answer in two parts.
1. The difference between activity!!
and requireActivity()
They both invoke getActivity()
and they both throw an exception if the Activity
is null. The only difference is the type of the returned exception and its message. Certainly, requireActivity()
throws a more explicit exception.
2. The "difference" between onActivityCreated()
and onCreateView()
The method onActivityCreated()
is invoked after onCreateView()
when both the Activity
and the Fragment
view are already created.
The method onCreateView()
is invoked before onActivityCreated()
when the Fragment
view should be still created.
In your scenario, there's no difference in where you put your Glide
usage. It would have been a difference if your Fragment
retains its instance or in the case the ImageView
is inside the Activity
.
By the way, I would move your Glide
usage in onViewCreated()
since onActivityCreated()
is going to be deprecated soon (https://developer.android.com/jetpack/androidx/releases/fragment#1.3.0-alpha02).
When to use onActivitycreate() and onCreate() in fragments
onActivitycreate() :
onActivitycreate()
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).
onCreate():
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
Read this doc for more details: Fragment Activity Life cycle
Android Fragments OnCreate vs OnCreateView
Sorry if the code looks out of line I'm answering from my phone
public class LiveGameTab1Fragment extends Fragment {
Bitmap bitmap;
Drawable iconDrawable;
public LiveGameTab1Fragment() {}
public LiveGameTab1Fragment(Context context
//add this if you need something from resources) {
//I don't know what you mean by icon.getIcon()
bitmap = BitmapFactory.decodeByteArray(icon.getIcon(), 0, icon.getIcon().length);
iconDrawable = new BitmapDrawable(context.getResources(), bitmap);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.live_game_tab1, container, false);
return V;
}
@Override //you need the onViewCreated function again I'm on my phone so I might be wrong about the variables inside so make sure to take the right code and the functions inside
public void onViewCreated(View v) {
super.onViewCreated(v);
//code moved to constructor so the image is initialize only ones
ImageButton imgButton = (ImageButton) v.findViewById(R.id.yourButtonId);
imgButton.setImageDrawable(iconDrawable);
}
}
Setup view inside onCreateView vs onActivityCreated
You can really use whatever you want, as long as it works.
However, I believe onViewCreated() is technically the "official" or recommended way to modify and reference your View after it's been created.
Related Topics
Android Get Free Size of Internal/External Memory
Checkbox in Recyclerview Keeps on Checking Different Items
Runtimeexception: Your Content Must Have a Listview Whose Id Attribute Is 'Android.R.Id.List'
How to Get the Absolute Coordinates of a View
How to Get the Width and Height of an Android.Widget.Imageview
Android Fragments and Animation
Generate Sha-1 for Flutter/React-Native/Android-Native App
Error "The Connection to Adb Is Down, and a Severe Error Has Occurred."
Using Intents to Pass Data Between Activities
How to Lock/Unlock Screen Programmatically
How to Add a Jar in External Libraries in Android Studio
Android View.Getdrawingcache Returns Null, Only Null
Push Notifications on Content Change
Android: How to Check If a View Inside of Scrollview Is Visible
How to Use Disk Caching in Picasso
Difference and Uses of Oncreate(), Oncreateview() and Onactivitycreated() in Fragments
Differencebetween Min Sdk Version/Target Sdk Version VS. Compile Sdk Version