Fragment Object and View Lifecycle
Fragment Object and View Lifecycle
1. What is a Fragment?
A Fragment represents a reusable part of an Activity’s UI.
A Fragment has:
1. A Fragment object lifecycle
2. A separate Fragment view lifecycle
This distinction is important because the Fragment object can continue existing even after its View has been destroyed.
---
2. Fragment lifecycle flow
onAttach()
|
onCreate()
|
onCreateView()
|
onViewCreated()
|
onViewStateRestored()
|
onStart()
|
onResume()
|
User interaction
|
onPause()
|
onStop()
|
onDestroyView()
|
onDestroy()
|
onDetach()---
3. Fragment object lifecycle
The Fragment object lifecycle represents the lifecycle of the actual Fragment instance.
Important callbacks:
* `onAttach()`
* `onCreate()`
* `onStart()`
* `onResume()`
* `onPause()`
* `onStop()`
* `onDestroy()`
* `onDetach()`The Fragment object can remain alive while it is present in the FragmentManager or back stack.
---
4. Fragment view lifecycle
The view lifecycle starts when the Fragment creates its View.
onCreateView()
|
View lifecycle begins
|
onViewCreated()
|
onStart()
|
onResume()
|
onPause()
|
onStop()
|
onDestroyView()
|
View lifecycle endsThe Fragment object may remain alive after onDestroyView().
Example:
Fragment object exists
|
Fragment View exists
|
Fragment added to back stack
|
Fragment View destroyed
|
Fragment object may remain---
## 5. `onCreate()`Use Fragment onCreate() for non-UI initialization.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Read arguments
// Initialize non-UI objects
}Suitable work:
* Read Fragment arguments
* Initialize non-view state
* Register Fragment result listeners
* Restore Fragment-level state
Do not access ViewBinding here because the Fragment View does not exist yet.
---
## 6. `onCreateView()`onCreateView() creates and returns the Fragment’s View.
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(
inflater,
container,
false
)
return binding.root
}A simpler alternative is to provide the layout directly:
class HomeFragment : Fragment(R.layout.fragment_home)---
## 7. `onViewCreated()`onViewCreated() is called after the Fragment View is created.
It is normally the best place for UI setup.
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
setupClickListeners()
observeUiState()
}Suitable work:
* Configure RecyclerView
* Set click listeners
* Initialize adapters
* Observe ViewModel data
* Update initial UI
* Configure child views
---
8. Observing data correctly
Use viewLifecycleOwner when the observer updates Fragment views.
viewModel.users.observe(viewLifecycleOwner) { users ->
binding.recyclerView.adapter =
UserAdapter(users)
}For Flow:
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(
Lifecycle.State.STARTED
) {
viewModel.uiState.collect { state ->
render(state)
}
}
}Do not use the Fragment object as the lifecycle owner for observations that access its View.
Bad:
viewModel.uiState.observe(this) {
binding.title.text = it.title
}The observer might remain active after the Fragment View is destroyed.
---
## 9. `onDestroyView()`onDestroyView() is called when the Fragment’s View is destroyed.
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}Clean up:
* ViewBinding references
* RecyclerView adapters when required
* View listeners
* Map or camera views
* View-specific callbacks
* Objects holding View references
Fragments can outlive their views, so ViewBinding references should be cleared in onDestroyView().
---
10. FragmentManager
FragmentManager manages Fragments inside an Activity or parent Fragment.
Responsibilities:
* Add Fragments
* Remove Fragments
* Replace Fragments
* Manage Fragment lifecycle
* Save and restore Fragment state
* Maintain the Fragment back stack
* Find existing Fragments
val fragmentManager = supportFragmentManagerInside a Fragment:
parentFragmentManager
childFragmentManagerDifference
parentFragmentManager
Manages the current Fragment
childFragmentManager
Manages Fragments inside the current Fragment---
11. Fragment transactions
A Fragment transaction contains one or more Fragment operations.
supportFragmentManager.beginTransaction()
.replace(
R.id.fragmentContainer,
DetailsFragment()
)
.addToBackStack(null)
.commit()Common operations:
add()
replace()
remove()
show()
hide()
attach()
detach()Every transaction must eventually be committed. Transactions can be added to the FragmentManager back stack so the user can reverse them using Back.
---
12. Fragment back stack
Suppose the app navigates through:
HomeFragment
|
DetailsFragment
|
PaymentFragmentBack stack:
Top
PaymentFragment
DetailsFragment
HomeFragment
BottomWhen Back is pressed:
PaymentFragment removed
|
DetailsFragment displayedUse:
.addToBackStack("details")Pop manually:
parentFragmentManager.popBackStack()---
13. Fragment state restoration
FragmentManager normally saves and restores added Fragments automatically.
Avoid adding the initial Fragment again after Activity recreation.
Bad:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment())
.commit()
}After rotation, this may replace the Fragment that FragmentManager already restored.
Better:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment())
.commit()
}
}---
14. Common Fragment mistakes
* Keeping binding after onDestroyView()
* Observing view data using the Fragment lifecycle
* Reusing removed Fragment instances
* Creating duplicate Fragments after rotation
* Performing transactions after state has already been saved
* Using Activity FragmentManager instead of child FragmentManager
* Passing large objects through Fragment arguments
---
Interview answer
> A Fragment has two lifecycles: the Fragment object lifecycle and the Fragment view lifecycle. The Fragment object may remain alive on the back stack while its View is destroyed. UI initialization belongs in onViewCreated(), and ViewBinding should be cleared in onDestroyView(). View-related observations should use viewLifecycleOwner. FragmentManager controls Fragment lifecycle, transactions, back stack and state restoration.