📋 Screens, Lists & Navigation · Lesson 24
Fragments & Fragment Lifecycle
What is a Fragment?
A Fragment is a reusable part of a screen with its own layout and lifecycle, living inside an Activity. Modern apps use one Activity (toolbar, drawer, bottom bar) and swap fragments for each screen.
Create a fragment
File → New → Fragment → Fragment (Blank), then clean it up to this pattern:
Kotlin – HomeFragment.kt
// HomeFragment.kt
class HomeFragment : Fragment() {
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
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnDetails.setOnClickListener {
(requireActivity() as MainActivity).showDetails("Maths")
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}Host it in an Activity
XML
<!-- activity_main.xml -->
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />Kotlin – MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) { // don't add again after rotation
supportFragmentManager.commit {
add(R.id.fragmentContainer, HomeFragment())
}
}
}
fun showDetails(subject: String) {
supportFragmentManager.commit {
setReorderingAllowed(true)
replace(R.id.fragmentContainer, DetailsFragment.newInstance(subject))
addToBackStack("details") // Back returns to HomeFragment
}
}
}Replace and the back stack
supportFragmentManager.commit { } comes from fragment-ktx. The Navigation Component (next lesson) does all of this for you with a graph.
Pass arguments
Kotlin – DetailsFragment.kt
class DetailsFragment : Fragment(R.layout.fragment_details) { // layout in the constructor
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentDetailsBinding.bind(view)
val subject = requireArguments().getString(ARG_SUBJECT) ?: "-"
binding.tvTitle.text = "Notes of $subject"
}
companion object {
private const val ARG_SUBJECT = "subject"
fun newInstance(subject: String) = DetailsFragment().apply {
arguments = bundleOf(ARG_SUBJECT to subject)
}
}
}Fragment lifecycle
Share data between fragments
Kotlin – activityViewModels()
// One ViewModel shared by every fragment of the Activity
class SharedViewModel : ViewModel() {
val selectedSubject = MutableLiveData<String>()
}
// ListFragment
private val shared: SharedViewModel by activityViewModels()
adapter.onClick = { shared.selectedSubject.value = it.name }
// DetailsFragment
private val shared: SharedViewModel by activityViewModels()
shared.selectedSubject.observe(viewLifecycleOwner) { binding.tvTitle.text = it }Common mistakes
- Adding the fragment in onCreate without checking
savedInstanceState == null→ two fragments on top of each other after rotation. - Using
bindingafteronDestroyView→ crash. observe(this)instead ofobserve(viewLifecycleOwner)→ duplicate updates and leaks.- Constructor parameters in a fragment → crash on recreation; use arguments.
Summary
- Fragment = screen part with own layout + lifecycle; one Activity hosts many.
- Pattern:
_bindingin onCreateView, setup in onViewCreated, clear in onDestroyView. - FragmentManager: add / replace / addToBackStack; arguments via
bundleOf. - Share data with
activityViewModels().
✅ Practice
Build an app with HomeFragment (list of 3 subjects) and DetailsFragment. Tapping a subject replaces the fragment with arguments; Back returns to the list.
Frequently Asked Questions
Activity or Fragment for a new screen?
Most modern apps use a single Activity and one Fragment per screen, connected by the Navigation Component. Fragments are lighter and share the toolbar, drawer and bottom navigation.
Why should I use viewLifecycleOwner instead of this in a fragment?
The fragment can live longer than its view (for example on the back stack). Observing with viewLifecycleOwner stops updates when the view is destroyed, avoiding crashes and leaks.
Can a fragment have a constructor with parameters?
No. Android recreates fragments with the empty constructor. Pass data with arguments (a Bundle) instead.
