0Pricing
Android Academy · Lesson

Fragments

Build modular UIs with Fragments. Learn the fragment lifecycle, ViewBinding in fragments, argument passing, back stack management, and fragment-activity communication.

Fragments is a free Android Academy lesson on CoddyKit — lesson 6 of 7. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 7 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Are Fragments?

A Fragment is a reusable UI module that lives inside an Activity. Think of it as a sub-Activity with its own layout, lifecycle, and logic.

Why use Fragments?

  • Reuse UI across multiple Activities
  • Handle different layouts for phone vs tablet
  • Build multi-screen flows without multiple Activities
  • Work naturally with Navigation Component

Fragment Lifecycle

Fragments have their own lifecycle that runs alongside the Activity lifecycle. Key callbacks:

  • onAttach — fragment attached to Activity
  • onCreate — fragment created (no view yet)
  • onCreateView — inflate the layout
  • onViewCreated — view ready, set up UI here
  • onDestroyView — view destroyed (clear view references)
  • onDetach — fragment detached

Creating a Fragment

Create a class that extends Fragment and override onCreateView to inflate the layout:

import androidx.fragment.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
}

ViewBinding in Fragments

Use ViewBinding in fragments — but release the binding in onDestroyView to avoid memory leaks:

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.tvTitle.text = "Welcome!"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null   // prevent memory leak
    }
}

Fragment Layout XML

Create res/layout/fragment_home.xml just like an Activity layout. The root view becomes the Fragment's view:

<!-- res/layout/fragment_home.xml -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="Home" />

</LinearLayout>

Adding a Fragment to Activity

Two ways to add a Fragment to an Activity:

  • Static (XML) — declare in the layout with <fragment> tag. Fixed at runtime.
  • Dynamic (code) — use FragmentManager and transactions. Can swap at runtime.
<!-- Static: in activity_main.xml -->
<fragment
    android:id="@+id/homeFragment"
    android:name="com.example.HomeFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Dynamic Fragment Transactions

Use supportFragmentManager to add, replace, or remove fragments at runtime:

// In Activity:
class MainActivity : AppCompatActivity(R.layout.activity_main) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .add(R.id.fragmentContainer, HomeFragment())
                .commit()
        }
    }

    fun showDetail(id: Int) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, DetailFragment.newInstance(id))
            .addToBackStack(null)  // allow back navigation
            .commit()
    }
}

Passing Arguments to Fragments

Pass data via a Bundle using the companion object factory pattern. Never use a Fragment constructor with parameters — Android recreates fragments with no-arg constructor after config changes:

class DetailFragment : Fragment() {

    companion object {
        private const val ARG_ID = "item_id"

        fun newInstance(itemId: Int): DetailFragment {
            return DetailFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_ID, itemId)
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val itemId = requireArguments().getInt(ARG_ID)
        // use itemId to load data
    }
}

Fragment → Activity Communication

Use an interface defined in the Fragment, implemented by the Activity. The Fragment gets a reference via onAttach:

class ListFragment : Fragment() {

    interface OnItemSelected {
        fun onItemSelected(id: Int)
    }

    private var listener: OnItemSelected? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as? OnItemSelected
    }

    private fun handleClick(id: Int) {
        listener?.onItemSelected(id)
    }

    override fun onDetach() {
        super.onDetach()
        listener = null
    }
}

Back Stack

When you call addToBackStack(null) in a transaction, pressing Back pops the fragment from the stack:

  • Without addToBackStack — Back exits the Activity
  • With addToBackStack — Back returns to the previous fragment
  • Use popBackStack() programmatically to navigate back

Fragment in a Container

The Activity layout just needs a container view — typically a FrameLayout with an ID. The Fragment fills that container:

<!-- activity_main.xml -->
<FrameLayout
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Quick Check

Why should you never pass constructor arguments to a Fragment and instead use a Bundle via a companion factory?

Recap: Fragments

Fragments are the building blocks of modern Android UIs:

  • Extend Fragment, inflate layout in onCreateView
  • Set up UI in onViewCreated
  • Release ViewBinding in onDestroyView
  • Pass data via Bundle + companion factory (newInstance)
  • Use addToBackStack for back navigation
  • Communicate with Activity via an interface

Next: request dangerous permissions at runtime.

Frequently asked questions

Is the “Fragments” lesson free?

Yes — the full text of “Fragments” is free to read here on the web, and the Android Academy course includes 7 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “Fragments”?

Build modular UIs with Fragments. Learn the fragment lifecycle, ViewBinding in fragments, argument passing, back stack management, and fragment-activity communication. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 6 of 7, so you can start here or from the beginning and move at your own pace.

How long does the “Fragments” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Project Structure & Manifest
  2. Activities & Lifecycle
  3. Layouts & Views
  4. Handling User Input
  5. Intents & Navigation
  6. Fragments
  7. Permissions & Runtime Requests
← Back to Android Academy