What is Fragment in Android? Lifecycle, Examples, and Usage
Fragments are one of the most important building blocks of modern Android apps. A Fragment lets you create reusable, modular sections of UI that live inside an Activity, making it easier to build flexible layouts, support phones and tablets, and manage complex navigation flows.
In this complete guide, you will learn what a Fragment is, how the Fragment lifecycle works, how it differs from an Activity, and how to implement Fragments with clear, beginner-friendly examples.
What Is a Fragment in Android?
A Fragment is a reusable piece of user interface and behavior that must be hosted by an Activity. It has its own layout, its own lifecycle, and can handle its own input events, but it cannot live independently without being attached to an Activity.
You can think of an Activity as a full “screen” and a Fragment as a “section” or “panel” of that screen. A single Activity can host one or multiple Fragments, and you can dynamically add, remove, or replace Fragments at runtime.
Why Fragments Were Introduced
Fragments were introduced to solve real-world problems in Android UI development, especially on larger devices like tablets. Before Fragments, each screen was usually a separate Activity, which made it harder to build multi-pane layouts or reuse UI pieces across different screens.
With Fragments, you can place two fragments side by side on a tablet (for example, a list on the left and details on the right), while reusing the same fragments in a single-pane layout on phones. This modularity also makes your code more organized and testable.
Key Characteristics of a Fragment
Some important characteristics of Android Fragments are:
- A Fragment must be hosted by an Activity (or another parent Fragment in some cases).
- It defines and manages its own layout and logic, separate from the Activity UI.
- It has its own lifecycle, which is closely tied to the lifecycle of the host Activity.
- Fragments can be added, removed, and replaced dynamically using the FragmentManager.
- Fragments are ideal for reusable UI components and multi-pane or responsive layouts.
Fragment Lifecycle Overview
The Fragment lifecycle is similar to, but more detailed than, the Activity lifecycle. It includes both fragment-specific callbacks and view-related callbacks. Understanding this lifecycle helps you know where to initialize views, start observing data, and clean up resources.
Main Fragment Lifecycle Callbacks
Here are the most commonly used Fragment lifecycle methods and what they are used for:
onAttach()– Called when the Fragment is first attached to its host Activity. The Activity context becomes available here.onCreate()– Called to do initial setup that does not involve the Fragment’s view, such as initializing variables or reading arguments.onCreateView()– Called to inflate the Fragment’s layout and return the root View that will be displayed on the screen.onViewCreated()– Called right after the view is created. Ideal for view initialization, binding views, setting adapters, and starting LiveData observers.onStart()– Fragment becomes visible to the user.onResume()– Fragment is visible and the user can interact with it.onPause()– User is leaving the Fragment (for example, another screen comes on top). Save transient state here if needed.onStop()– Fragment is no longer visible.onDestroyView()– Called when the Fragment’s view hierarchy is being removed. Clear any references to views here to avoid memory leaks.onDestroy()– Final cleanup of Fragment state.onDetach()– Fragment is detached from the Activity; the context is no longer valid.
A key point is that the Fragment’s view lifecycle (from onCreateView() to onDestroyView()) is separate from the Fragment’s own lifecycle. You should not keep long-lived references to views beyond onDestroyView().
Creating a Simple Fragment – Step by Step
Let’s create a simple example: a Fragment that shows a welcome message on the screen. You will see how to define its layout, implement the class, and attach it to an Activity.
Step 1: Create the Fragment Layout
In your res/layout folder, create a new XML layout file named fragment_welcome.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tvWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Fragment example"
android:textSize="20sp" />
</LinearLayout>
This layout defines a simple centered TextView that will be displayed inside the Fragment.
Step 2: Create the Fragment Class
Now create a Kotlin class named WelcomeFragment.kt that extends Fragment and inflates this layout:
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class WelcomeFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Non-UI initialization (if needed)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the fragment layout
return inflater.inflate(R.layout.fragment_welcome, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Access views here, set listeners, bind data, etc.
}
}
The Fragment inflates its layout in onCreateView() and can safely work with views in onViewCreated().
Step 3: Add a Container in the Activity Layout
In your Activity’s layout (for example, activity_main.xml), define a container where the Fragment will be placed. A FrameLayout is a common choice:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
This container acts as a placeholder where you will dynamically add or replace Fragments.
Step 4: Attach the Fragment from the Activity
In your MainActivity.kt, use the supportFragmentManager to add the Fragment when the Activity is created:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, WelcomeFragment())
.commit()
}
}
}
When the Activity starts, it loads WelcomeFragment into the fragmentContainer. From here, you can later replace this Fragment with another one to navigate between different pieces of UI without changing the Activity.
Common Types of Fragments and Usage Patterns
In real apps, Fragments are used in many different ways. Here are a few common patterns:
- List and Detail Fragments – One Fragment shows a list of items, and another Fragment shows the details for a selected item. On phones, these might appear on separate screens; on tablets, both can be shown side by side.
- DialogFragment – A Fragment that displays a dialog-style UI on top of the current screen, ideal for confirmations, forms, or alerts.
- ViewPager / Tabs with Fragments – Each tab or page is implemented as a Fragment, making it easy to swipe between screens while keeping logic modular.
Using Fragments in these patterns helps you keep your code organized and reuse entire sections of UI across Activities or navigation flows.
Best Practices for Working with Fragments
To use Fragments effectively and avoid common bugs, follow these best practices:
- Keep UI-related logic inside Fragments and let the Activity focus on high-level navigation and coordination.
- Use
onViewCreated()andonDestroyView()to manage view references, adapters, and observers, so you do not leak views after the Fragment’s view is destroyed. - Pass data to Fragments using arguments (the
argumentsBundle) instead of calling setters directly, so state can be properly restored after configuration changes. - Use the Jetpack Navigation Component to manage navigation and Fragment transactions in a safe, declarative way.
- Avoid doing heavy work on the main thread in Fragment callbacks; offload background work to coroutines, background threads, or other async mechanisms.
Fragment vs Activity – Quick Recap
Although this article focuses on Fragments, it helps to quickly recap how they differ from Activities:
- An Activity is a full screen and can exist on its own; a Fragment is a section of UI that must live inside an Activity.
- Activities are declared in the manifest; Fragments are not and are managed via the FragmentManager.
- Fragments are more reusable and are ideal for modular, flexible UIs, while Activities define the higher-level screen and navigation structure.
In a modern Android architecture, a common pattern is to use one main Activity that hosts multiple Fragments, each representing a distinct screen or feature.
To learn more about Fragment vs Activity, we’ve already published a detailed article on this topic. Please refer to that article for an in-depth explanation.
Conclusion
Fragments in Android provide a powerful way to build modular, reusable, and flexible user interfaces. By understanding what a Fragment is, how its lifecycle works, and how to attach it to an Activity, you can design screens that adapt to different devices and are easier to maintain.
With the example and best practices in this guide, you are ready to start using Fragments to build real-world Android apps—whether you are implementing simple single-pane screens or complex, multi-pane experiences for phones and tablets.

0 Comments