Difference Between Android Activity vs Fragment

Difference Between Android Activity vs Fragment (Clear Comparison for Beginners)

“Activity vs Fragment” is one of the most common questions for new Android developers. Both are key building blocks of Android UIs, but they serve different purposes and behave differently in terms of lifecycle, navigation, and reuse. In this complete, beginner-friendly guide, you will learn what Activities and Fragments are, how they differ, when to use each, and how they work together in a modern Android app.


What Is an Activity in Android?

An Activity represents a single, focused screen with which the user can interact. It manages a window on the device and typically hosts your views or fragments. When you open an app from the launcher, you are usually entering its main Activity.

Activities are entry points for user interaction: they handle lifecycle events like onCreate(), onStart(), onResume(), and they respond to user actions, system callbacks, and navigation transitions. You can think of an Activity as a full screen page in your app’s flow, such as a login screen, home screen, or settings screen.

To learn more about Activity, we’ve already published a detailed article on this topic. Please refer to that article for an in-depth explanation.

What Is a Fragment in Android?

A Fragment is a reusable portion of the user interface and behavior that must be hosted inside an Activity. It has its own layout, its own lifecycle, and its own logic, but it cannot exist on its own without an Activity.

Fragments were introduced to help build more flexible and modular UIs, especially for tablets and multi-pane layouts. You can combine multiple fragments inside a single Activity, replace them at runtime, and reuse the same fragment class in different Activities or configurations (for example, phone vs tablet).

To learn more about Fragment, we’ve already published a detailed article on this topic. Please refer to that article for an in-depth explanation.

High-Level Difference: Page vs Section

The simplest way to remember the difference is:

  • Activity = a full screen or “page” of your app.
  • Fragment = a modular “section” or piece of UI inside that page.

Think of an Activity as a container or host, and Fragments as interchangeable blocks you can add, remove, or replace inside that container.

Activity vs Fragment: Key Differences at a Glance

The table below summarizes the most important differences between an Activity and a Fragment in Android:

Activity Fragment
Represents a full screen or independent UI where the user interacts with the app. Represents a portion of the UI or behavior inside an Activity.
Can exist independently; the system can launch it via an Intent. Cannot exist alone; must be attached to a host Activity.
Declared in AndroidManifest.xml with an <activity> tag. Not declared in the manifest; managed dynamically with FragmentManager.
Lifecycle is managed directly by the Android system. Lifecycle is closely tied to the host Activity’s lifecycle.
Navigation between Activities uses Intents and the system back stack. Navigation between Fragments uses FragmentManager and a fragment back stack.
Less reusable; usually designed for one specific screen. Highly reusable; the same Fragment can be used in multiple Activities/layouts.
Heavier component; switching Activities is more expensive. Lighter component; swapping Fragments is usually cheaper and smoother.

Activity Lifecycle vs Fragment Lifecycle

Both Activities and Fragments have lifecycles, but they are not identical. Understanding the difference helps you know where to initialize views, subscribe to data, or release resources.

Activity Lifecycle (Simplified)

A typical Activity lifecycle includes:

  • onCreate() – Initialize the Activity, set the content view, set up ViewBinding or DataBinding, create ViewModel, etc.
  • onStart() – Activity becomes visible to the user.
  • onResume() – Activity is in the foreground and user can interact.
  • onPause() – Activity is partially obscured; pause ongoing actions.
  • onStop() – Activity is no longer visible; release heavy resources.
  • onDestroy() – Activity is about to be destroyed; final cleanup.

The system manages this lifecycle and adds the Activity to a global back stack so the user can navigate back using the system Back button, unless you customize this behavior.

Fragment Lifecycle (Simplified)

A Fragment shares some lifecycle callbacks with Activities but also has additional, fragment-specific ones:

  • onAttach() – Fragment is attached to its host Activity.
  • onCreate() – Initial setup; non-UI initialization.
  • onCreateView() – Inflate and return the Fragment’s view hierarchy.
  • onViewCreated() / onActivityCreated() – Views are ready; bind data, set listeners.
  • onStart(), onResume() – Fragment becomes visible and interactive.
  • onPause(), onStop() – Fragment not in the foreground.
  • onDestroyView() – Fragment’s view hierarchy is destroyed; clear view references.
  • onDestroy(), onDetach() – Fragment is destroyed and detached from Activity.

The host Activity’s lifecycle drives the Fragment lifecycle. For example, when the Activity is destroyed, its Fragments are also destroyed. This tight coupling is why Fragments are great for modular, UI-level behavior that depends on a parent screen.

Navigation and Back Stack Differences

Another key difference between Activity and Fragment is how navigation and the back stack are handled.

  • Activity back stack – Managed by the Android system. When you start a new Activity with an Intent, the previous one goes to the back stack. Pressing Back pops the top Activity and returns to the previous one.
  • Fragment back stack – Managed by the host Activity’s FragmentManager. When you perform a fragment transaction and call addToBackStack(), that transaction can be reversed when the Back button is pressed.

In modern “single-Activity” architectures, developers often keep one main Activity and navigate between screens by adding, replacing, and popping Fragments, sometimes using the Jetpack Navigation Component for smoother navigation handling.

Use Cases: When to Use Activity vs Fragment

Choosing between Activities and Fragments becomes easier when you focus on intent and scope.

When to Use an Activity

  • For high-level, independent screens or entry points (for example, login, main/home, onboarding).
  • When you need a separate task or different intent filters (for example, an Activity that handles “Share” or “Open with” intents).
  • When a screen stands alone and does not have to share much UI logic with other screens.

When to Use a Fragment

  • For reusable pieces of UI, such as lists, detail panes, or reusable panels.
  • When building multi-pane layouts (for example, master–detail layouts on tablets and landscape phones).
  • When you want to keep a single Activity and swap different screens inside it using the FragmentManager or Navigation Component.

In many modern projects, a recommended architecture is “single-Activity, multiple-Fragments,” where the Activity mostly handles navigation and top-level chrome (like a toolbar), while Fragments hold most of the screen-specific UI and logic.

Example: Activity Hosting a Fragment

To understand how they work together, let’s look at a simple example where an Activity hosts a Fragment that displays a welcome message.

Step 1: Create the Fragment Layout

Create a layout file, for example 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 Fragment"
        android:textSize="20sp" />

</LinearLayout>
  

Step 2: Create the Fragment Class

Create a Kotlin class WelcomeFragment.kt:

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 onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the fragment layout
        return inflater.inflate(R.layout.fragment_welcome, container, false)
    }
}
  

Step 3: Activity Layout with a Fragment Container

In your Activity layout (for example, activity_main.xml), define a container where the Fragment will be placed:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  

Step 4: Add the Fragment from the Activity

In your MainActivity.kt, use the supportFragmentManager to add the Fragment:

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()
        }
    }
}
  

In this example, the Activity exists as the top-level screen, while the Fragment represents a modular section that can be easily replaced with another Fragment later (for example, a details screen or list screen) without changing the Activity code.

Pros and Cons: Activity vs Fragment

Both components have strengths and trade-offs.

Advantages of Activities

  • Natural entry points for the system and other apps via Intents.
  • Simpler mental model for very small apps with just a few screens.
  • Clear separation between distinct tasks or flows.

Advantages of Fragments

  • Highly reusable and modular UI components.
  • Easier to support multi-pane layouts and responsive design.
  • Smoother transitions and more lightweight than switching whole Activities.

The best real-world apps typically combine both: Activities as top-level containers, Fragments to implement the majority of actual screens.

Conclusion

The difference between an Android Activity and a Fragment is mainly about scope and responsibility. An Activity is a full-screen entry point that manages a window and participates directly in the system’s navigation. A Fragment is a modular, reusable portion of UI and behavior that lives inside an Activity and shares its lifecycle.

By understanding how Activities and Fragments differ in lifecycle, navigation, reusability, and use cases, you can design cleaner architectures, build flexible UIs, and write code that scales from simple apps to complex, multi-pane experiences on phones and tablets.



Post a Comment

0 Comments