avatarAbdul Qadir

Summary

The web content provides an in-depth explanation of the Fragment lifecycle in Android development, focusing on when to use the onCreate, onCreateView, and onViewCreated methods.

Abstract

The article "Deep dive into Fragments when to use onCreate(), onCreateView and onViewCreated()" elucidates the purpose and appropriate usage of key lifecycle methods in Android Fragments. It emphasizes that a Fragment is a modular, reusable component within an activity, with its own lifecycle. The onAttach method is called when a Fragment is first attached to its context, allowing access to the activity. The onCreate method is used for non-graphical initialization that doesn't involve the View hierarchy. onCreateView is designated for inflating the fragment's layout and should be paired with onDestroyView to release the view. Lastly, onViewCreated is used for final initializations after the view hierarchy is created, such as modifying UI elements. The article also notes the deprecation of onActivityCreated(Bundle) since API level 28.

Opinions

  • The author suggests that onCreate is the right place for initializations that do not require the View hierarchy, such as setting up a location client or assigning variables.
  • It is implied that onCreateView should be used exclusively for inflating the layout and not for setting up the view, which should be done in onViewCreated.
  • The article conveys the importance of releasing resources in onDestroyView that were allocated in onCreateView to prevent memory leaks.
  • The author emphasizes that onViewCreated is the safe place to perform UI-related initializations since the view hierarchy is guaranteed to be non-null.
  • The deprecation of onActivityCreated(Bundle) is highlighted, suggesting that developers should migrate initializations previously done in this method to onViewCreated or onCreate.
  • An opinion on cost-effectiveness is presented, with a recommendation for an AI service that offers similar capabilities to ChatGPT Plus (GPT-4) at a lower price point.

Deep dive into Fragments when to use onCreate(), onCreateView and onViewCreated()

Fragments

A Fragment is a piece of an activity which enable more modular activity design. We can say that a fragment is lite weight and is a kind of sub-activity. A fragment has its own layout and its own behavior with its own life cycle callbacks. You can add or remove fragments in an activity while the activity is running.

Activity state and fragment callbacks

Some of the methods of Framents during activity create state:

  1. onAttach()
  2. onCreate()
  3. onCreateView()
  4. onViewCreated()
  5. onActivityCreated(Bundle) — depreciated in api 28
fragment methods
  1. onAttach()

Called when a fragment is first attached to its context. it's called before onCreate(). After onAttach() activity we can access to the activity by getActivity() method.

Example:

override fun onAttach(context: Context) {
        super.onAttach(context)
        // here we can access the activity once the fragment is attach
        activity?.lifecycle?
        Log.d("Fragment1", "onAttach")
    }

2. OnCreate()

OnCreate() is called for the initial creation of a fragment. This is called after onAttach(Context) and before onCreateView(LayoutInflater, ViewGroup, Bundle).

In this method, you can do work that is not related to the interface. For example, prepare the adapter.

OnCreate() can be called while the fragment’s activity is still in the process of being created. As such, you cannot rely on things like the activity’s content view hierarchy being initialized at this point.

When to use onCreate()? OnCreate() can be used to assign variables, to get Intent extras, to get the location and anything else that doesn't involve the View hierarchy or non-graphical initialization which needs to be called in the beginning of fragment creation.

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. As such, you cannot rely on things like the activity’s content view hierarchy being initialized at this point.

Example:

override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   //fused location and setHasOptionsMenu do not required view hierarchy
   setHasOptionsMenu(true)
   
   fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}

3. OnCreateView()

OnCreateView() is recommended to only inflate the layout.

onCreateView() will be called between onCreate(Bundle) and onActivityCreated(Bundle).

*******************When to use onCreateView()***********************

It can be used to create components and inflate the layout through the inflate() method of the Inflater object. Note: If we want to return a View from OnCreateView(), we will also have to call in onDestroyView when the view is being released.

Example:

override fun onCreateView(
   inflater: LayoutInflater, container: ViewGroup?,
   savedInstanceState: Bundle?
): View? {
   val view = inflater.inflate(R.layout.fragment1, container, false)
   Log.d("Fragment1", "onCreateView")
   
   return view
}

// here we have to destroy the view, if we return view from on create
override fun onDestroyView() {
   super.onDestroyView()
   view = null
}

4. onViewCreated()

onViewCreated() is called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment’s view hierarchy is not however attached to its parent at this point.

**************************When to Use ***********************

onViewCreated() is called after onCreateView() and ensures that the fragment’s root view is non-null . Here we can declare the objects required by theContext and is mainly used for final initialisations (for example, modifying UI elements).

Example:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.name ="test"
    binding.recylerview = recyclerview
}

5. onActivityCreated(Bundle)

Called when the onCreate() activity method is triggered, which means that the fragment can access the activity components.

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).

**************** Note *************************

This method is deprecated from API level 28.

Android App Development
Kotlin
Android
Mobile App Development
Recommended from ReadMedium