Where is better to use View Binding in Fragments? (onCreateView vs onViewCreated)
It's good practice to use initialize binding in onCreateview
as its will inflate the layout the same moment the view creates and then use this inside onViewCreated
and other functions.
Also you need to make _binding = null
in onDestroyView
to prevent the leaks.
Difference between onCreateView and onViewCreated in Fragment - Kotlin
As per your comments, you did something like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
hello() // the method has already returned a View, so this call is never reached.
}
So, when you call hello()
in onCreateView
after the return statement,
the method has no effect because of the return statement.
Since onViewCreated
is called after the onCreateView
,
the underlying View
is no more null
in your hello
function.
If you still want to use onCreateView
, you can do something like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentView = inflater.inflate(R.layout.fragment_home, container, false)
hello(fragmentView)
return fragmentView
}
fun hello(buttonHolderView: View?) {
val button = buttonHolderView?.findViewById<Button>(R.id.button_login)
button?.setOnClickListener {
val action = homeFragmentDirections.actionHomeFragmentToLoginFragment()
findNavController().navigate(action)
Toast.makeText(context, "wao", Toast.LENGTH_LONG).show()
}
}
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
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()
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.
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.
Related Topics
Open an Image Using Uri in Android's Default Gallery Image Viewer
Android: Speech Recognition Without Using Google Server
Getexternalstoragepublicdirectory Deprecated in Android Q
Apply a Theme to an Activity in Android
Sharing Data Between Fragments Using New Architecture Component Viewmodel
How to Create Text File and Insert Data to That File on Android
Error Message 'Java.Net.Socketexception: Socket Failed: Eacces (Permission Denied)'
Android Set Up Volley to Use from Cache
Handle Screen Rotation Without Losing Data - Android
Why My App Is Not Showing Up on Tablets in Google Play
Show an Alert Dialog in Broadcast Receiver After a System Reboot
What Proguard Configuration Do I Need for Firebase on Android
Android Push Notification (Gcm), Is There Any Daily Limit
How to Maintain Multi Layers of Imageviews and Keep Their Aspect Ratio Based on the Largest One
Manifest Merger Fails for Appcomponentfactory