Fundamental Things to Know in Android Activity and Fragment

Post Date: June 12, 2019
Last Updated: November 13, 2026

Introduction

Activities and Fragments are two fundamental components of Android application development. They help developers organize an application’s user interface, manage screen navigation, and handle user interactions.

An Activity represents a screen or entry point into an Android application, while a Fragment represents a reusable portion of the user interface hosted within an Activity or another Fragment.

Understanding the differences between Activities and Fragments, their lifecycle methods, and how to navigate between them is essential when developing Android applications.

In this article, we will explore the basic concepts of Android Activities and Fragments, their lifecycle methods, and how to perform Fragment transactions using Java.

1. What Is an Activity in Android?

An Activity is a core Android application component that provides a window in which an application displays its user interface.

An Activity generally represents a single screen of an application. For example, a shopping application might contain separate screens for:

  • Login
  • Home
  • Product details
  • Shopping cart
  • User profile

Each screen can be implemented using an Activity, although modern Android applications often use a single-Activity architecture with multiple Fragments or other navigation destinations.

An Activity works with a layout file to display its user interface. For example, an XML layout can define buttons, text fields, images, and other UI components.

Declaring an Activity in AndroidManifest.xml

Before an Activity can be launched as part of your application, it must be declared in the application’s manifest.

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:label="My Application"
        android:theme="@style/Theme.MyApplication">

        <activity
            android:name=".ExampleActivity"
            android:exported="false" />

    </application>

</manifest>

The android:name attribute specifies the Activity class.

For an Activity that serves as the application’s launcher entry point, configure the appropriate MAIN action and LAUNCHER category intent filter. On Android 12 and later, components with intent filters must explicitly declare android:exported.

Creating an Activity

To create an Activity, define a class that extends an Android Activity class, such as AppCompatActivity.

Example:

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class ExampleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
    }
}

The onCreate() method is called when the system creates the Activity.

It is commonly used to:

  • Initialize the Activity.
  • Load the user interface.
  • Initialize UI components.
  • Set up event listeners.
  • Restore previously saved state when available.

The setContentView() method connects the Activity to its XML layout file.

An Activity can launch another Activity using an Intent.

For example, to open SecondActivity from MainActivity:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);

An Intent describes an operation to perform. It can be used to launch another Activity, pass data between components, and interact with other Android applications.

To pass data to another Activity:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

intent.putExtra("username", "John");

startActivity(intent);

The receiving Activity can retrieve the value:

String username = getIntent().getStringExtra("username");

2. Android Activity Lifecycle

Every Activity has its own lifecycle. The Android operating system manages this lifecycle by calling specific callback methods as the Activity changes its state.

Understanding these callbacks helps developers manage resources, handle interruptions, and maintain application state.

The main Activity lifecycle methods are:

  1. onCreate()
  2. onStart()
  3. onResume()
  4. onPause()
  5. onStop()
  6. onRestart()
  7. onDestroy()

Activity Lifecycle Methods

1. onCreate()

The onCreate() method is called when the Activity is first created.

It is used to initialize essential components, load the layout, and prepare the Activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

The savedInstanceState parameter contains previously saved instance state when available. It can be null when no saved state exists.

2. onStart()

The onStart() method is called when the Activity becomes visible to the user.

It prepares the Activity to enter the foreground.

@Override
protected void onStart() {
    super.onStart();
    // Prepare resources needed while the Activity is visible
}

3. onResume()

The onResume() method is called when the Activity enters the foreground and becomes ready for user interaction.

This is where developers can initialize functionality that should be active while the user interacts with the screen.

@Override
protected void onResume() {
    super.onResume();
    // Resume UI-related operations
}

4. onPause()

The onPause() method is called when the Activity loses foreground focus.

This does not necessarily mean that the Activity is completely hidden. For example, a partially transparent Activity or a multi-window situation can cause the current Activity to become paused while remaining visible.

It is commonly used to pause operations that should not continue while the Activity is not in the foreground.

@Override
protected void onPause() {
    super.onPause();
    // Pause foreground-only operations
}

Keep this callback lightweight. Avoid performing lengthy database operations or network requests here.

5. onStop()

The onStop() method is called when the Activity is no longer visible to the user.

It is useful for releasing resources and stopping operations that are unnecessary while the Activity is hidden.

@Override
protected void onStop() {
    super.onStop();
    // Release resources not needed while the Activity is hidden
}

6. onRestart()

The onRestart() method is called when a previously stopped Activity is about to become visible again.

It is followed by onStart().

@Override
protected void onRestart() {
    super.onRestart();
    // Prepare the Activity to become visible again
}

7. onDestroy()

The onDestroy() method is called before an Activity is destroyed.

This can happen when the Activity finishes or when the system recreates it due to a configuration change, such as device rotation.

@Override
protected void onDestroy() {
    super.onDestroy();
    // Clean up remaining resources
}

Important: The Android system can terminate an application process without calling onDestroy(). Therefore, do not rely on this method as the only place to save important application data.

Activity Lifecycle Flow

The simplified Activity lifecycle follows this sequence:

        onCreate()
            |
        onStart()
            |
        onResume()
            |
       User interacts
            |
        onPause()
          /    \
         /      \
    onResume()  onStop()
                  |
              onRestart()
                  |
               onStart()
                  |
              onResume()

        Or from onStop():

             onDestroy()

Understanding this lifecycle helps developers manage application resources and provide a consistent user experience.

3. What Is a Fragment in Android?

A Fragment represents a reusable portion of an application’s user interface.

A Fragment has its own lifecycle, manages its own UI, and can handle user interactions. However, unlike an Activity, a Fragment cannot exist independently. It must be hosted by an Activity or another Fragment.

You can think of a Fragment as a modular section of an Activity that can be added, removed, or replaced while the Activity is running.

For example, an application might use different Fragments for:

  • Home screen content
  • User profile
  • Product details
  • Settings
  • Search results

Fragments help developers create modular and reusable application interfaces.

Creating a Fragment

To create a Fragment, extend the AndroidX Fragment class.

Example:

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ExampleFragment extends Fragment {

    public ExampleFragment() {
        super(R.layout.fragment_example);
    }
}

The fragment_example.xml file defines the user interface for this Fragment.

For example:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to Example Fragment"
        android:textSize="20sp" />

</LinearLayout>

The Fragment class manages the layout and its lifecycle within the hosting Activity.

4. Understanding the Fragment Lifecycle

Similar to an Activity, a Fragment has its own lifecycle.

Some important Fragment lifecycle callbacks include:

Lifecycle methodPurpose
onAttach()Called when the Fragment is attached to its host.
onCreate()Initializes Fragment-level state.
onCreateView()Creates the Fragment’s user interface.
onViewCreated()Called after the Fragment’s view has been created.
onStart()Makes the Fragment visible.
onResume()Allows the Fragment to interact with the user.
onPause()Called when the Fragment loses foreground interaction.
onStop()Called when the Fragment is no longer visible.
onDestroyView()Called when the Fragment’s view hierarchy is destroyed.
onDestroy()Cleans up Fragment-level state.
onDetach()Called when the Fragment is detached from its host.

Important: Fragment View Lifecycle

A Fragment’s lifecycle and its view lifecycle are separate.

For example, when a Fragment is placed on the back stack, its view can be destroyed while the Fragment instance remains managed by the FragmentManager.

Use onDestroyView() to clean up references to views and view binding objects.

This distinction is important when managing UI resources and preventing memory leaks.

5. What Are Fragment Transactions?

Fragment transactions allow developers to add, remove, replace, show, or hide Fragments dynamically.

For example, suppose an application has a MainActivity with a container that displays different Fragments.

To navigate to another Fragment, we can use the FragmentManager and FragmentTransaction classes.

Step 1: Create a Fragment Container

First, define a container in the Activity layout.

Example: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Step 2: Create a New Fragment

Create a Fragment class named ExampleFragment.

import androidx.fragment.app.Fragment;

public class ExampleFragment extends Fragment {

    public ExampleFragment() {
        super(R.layout.fragment_example);
    }
}

Step 3: Perform a Fragment Transaction

Now, use the FragmentManager to replace the existing Fragment with the new Fragment.

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            Fragment newFragment = new ExampleFragment();

            FragmentManager fragmentManager =
                    getSupportFragmentManager();

            FragmentTransaction transaction =
                    fragmentManager.beginTransaction();

            transaction.replace(
                    R.id.fragment_container,
                    newFragment
            );

            transaction.addToBackStack(null);
            transaction.commit();
        }
    }
}

Explanation:

  • getSupportFragmentManager() obtains the FragmentManager associated with the Activity.
  • beginTransaction() starts a new Fragment transaction.
  • replace() replaces the Fragment currently displayed in the specified container.
  • addToBackStack(null) adds the transaction to the back stack, allowing the user to return to the previous Fragment using the Back button.
  • commit() schedules the transaction to be executed.

The savedInstanceState == null condition prevents the initial Fragment from being added again when the Activity is recreated after a configuration change.

6. Difference Between Activity and Fragment

Both Activities and Fragments are important Android components, but they serve different purposes.

ActivityFragment
Represents an application screen or entry point.Represents a reusable portion of the UI.
Can exist independently within the application.Must be hosted by an Activity or another Fragment.
Declared in the Android manifest.Managed through a FragmentManager.
Uses Activity lifecycle callbacks.Has its own lifecycle and view lifecycle.
Can launch another Activity using an Intent.Can be added, removed, or replaced using Fragment transactions.
Provides a window for the application UI.Displays its UI within the host’s view hierarchy.

Conclusion

Activities and Fragments are fundamental concepts in Android application development.

An Activity provides the application screen and manages its lifecycle, while a Fragment provides a modular and reusable section of the user interface.

Understanding their lifecycle methods, navigation mechanisms, and Fragment transactions helps developers build maintainable Android applications.

Although Activities and Fragments can both be used to organize application screens, choosing the appropriate component depends on the application’s architecture and navigation requirements.

Frequently Asked Questions

1. What is the main difference between Activity and Fragment in Android?

An Activity represents an application screen or entry point, whereas a Fragment represents a reusable portion of the UI that must be hosted by an Activity or another Fragment.

2. Can a Fragment exist without an Activity?

No. A Fragment must be hosted by an Activity or another Fragment. It cannot operate independently.

3. What is the purpose of onCreate() in Android Activity?

The onCreate() method initializes the Activity, loads its layout, and prepares the components required for the screen.

4. What is a Fragment transaction in Android?

A Fragment transaction is a set of operations used to add, remove, replace, show, or hide Fragments within an application’s UI.

5. What is the difference between onDestroy() and onDestroyView()?

onDestroyView() is called when a Fragment’s view hierarchy is destroyed. onDestroy() is called when the Fragment instance itself is being destroyed.

References

Need Assistance?

Need help with Android application development, Activity and Fragment implementation, or troubleshooting Android application issues?

The Pheonix Solutions technical team can assist you with Android development, application maintenance, and troubleshooting.

For assistance, contact us.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Comment

Scroll to Top