Fragment: What It Is, Fragments and FragmentManager in Android

Author: IT Sectr Published: 2026-02-22 Reading time: 7 min

Fragment is a reusable UI component in Android that is embedded into an Activity and managed through FragmentManager. Each fragment has its own lifecycle, layout, and state. Fragment simplifies adaptation to different screen sizes and code reuse. Read more in the official Google guide.

Key Takeaways

  • Fragment — a UI component inside an Activity with its own lifecycle and layout
  • FragmentManager — a class for managing fragment transactions and back stack
  • FragmentTransaction — an atomic operation for adding, replacing, or removing fragments
  • Jetpack Fragment — a library for backward compatibility down to Android 1.6 (API 4)
  • ViewModel — a shared component for data exchange between fragments in one Activity

What is Fragment?

Fragment is a modular Android user interface component that represents a part of the screen inside an Activity. Fragment can manage its own layout, handle lifecycle events, and save its state. Due to modularity, one fragment can be used in different Activities and on different devices.

Fragment API appeared in Android 3.0 (Honeycomb, API 11) in 2011 to support tablets. Before that, developers had to create separate Activities for phone and tablet. Fragment made it possible to assemble a screen from independent blocks. In 2019, Google released the Jetpack Fragment library with backward compatibility down to API 4.

According to Google (2026), 80% of apps in Google Play use Fragment in some form. Jetpack Fragment library has been downloaded over 10 billion times via Google Play Services. Fragment remains a key component of Android architecture even in the era of Jetpack Compose.

Fragment Lifecycle

The lifecycle of Fragment is more complex than that of Activity because it depends on the state of the host Activity. Fragment goes through the same states as Activity but adds its own callbacks: onAttach, onCreateView, onViewCreated, onActivityCreated, onDestroyView, onDetach.

Fragment CallbackActivity EquivalentPurpose
onAttachbefore onCreateFragment attached to Activity
onCreateonCreateInitialization of non-UI data
onCreateViewonCreateCreating layout via inflater
onViewCreatedonCreateBinding UI elements after view creation
onDestroyViewonDestroyRemoving view, releasing UI resources
onDetachonDestroyFragment detached from Activity

Comparing Fragment and Activity Lifecycle

The main difference of Fragment lifecycle is the invocation of onCreateView and onDestroyView between onCreate and onDestroy. Fragment can exist without UI (if onCreateView returns null). After Activity recreation, FragmentManager automatically restores fragments.

FragmentManager and Transactions

FragmentManager is the central class for managing fragments in an Activity. It handles adding, removing, replacing fragments, managing back stack, and restoring state. FragmentManager is available via supportFragmentManager (AndroidX) or fragmentManager (old API).

kotlin
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Fragment not yet added — creating
        if (savedInstanceState == null) {
            val transaction = this.supportFragmentManager
                .beginTransaction()
            transaction.add(R.id.fragment_container, ListFragment())
            transaction.addToBackStack(null)
            transaction.commit()
        }
    }

    fun replaceFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .addToBackStack(null)
            .commit()
    }
}

FragmentTransaction transactions are atomic. commit() schedules execution for the next Looper cycle. For immediate execution use commitNow(). addToBackStack(null) adds the transaction to the back stack — the back button will undo the operation.

Fragment Lifecycle Methods

Let's look at the key methods of the Fragment lifecycle with a Kotlin example. onCreateView creates a layout — unlike Activity, the method must return a View. onViewCreated is called immediately after, here it is safe to find elements by id. onDestroyView is the last moment to clear view references.

kotlin
class DetailFragment : Fragment() {

    private var _binding: FragmentDetailBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentDetailBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.textTitle.setText("Details")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

The View Binding pattern with _binding/binding ensures that after onDestroyView the layout reference is nullified. Accessing binding after view destruction will throw NullPointerException. This pattern is recommended by Google for all fragments.

Data Transfer Between Fragments

For data transfer between fragments, Android offers several mechanisms. The most reliable is a shared ViewModel, shared between fragments of one Activity. Fragment Result API is suitable for one-time events. Bundle arguments are for data when creating a fragment.

kotlin
// Shared ViewModel for two fragments
class SharedViewModel : ViewModel() {
    private val _selectedItem = MutableLiveData<Item>()
    val selectedItem: LiveData<Item> = _selectedItem

    fun select(item: Item) { _selectedItem.setValue(item) }
}

// Fragment A: sends event via Fragment Result API
setFragmentResult("request_key", bundleOf("key" to "value"))

// Fragment B: receives event
childFragmentManager.setFragmentResultListener("request_key", this) { requestKey, bundle ->
    val value = bundle.getString("key")
}

Fragment Result API (added in Fragment 1.3.0) replaces the deprecated setTargetFragment/onActivityResult. The API is type-safe, uses Bundle, and does not require knowledge of the recipient. Parent FragmentManager acts as an intermediary between fragments.

Fragment vs Activity: When to Choose What

The choice between Fragment and Activity depends on the application architecture. Fragment is mandatory for adaptive layouts (phone + tablet), for custom transition animations, and for using Jetpack Navigation. Activity is preferable for simple apps with one or two screens.

CriterionFragmentActivity
Creation speedFaster (lightweight component)Slower (system process)
ReusabilityHigh (one fragment in different Activities)Low (each screen has its own Activity)
Transition animationFlexible (FragmentTransaction)Limited (overridePendingTransition)
Preservation on rotationAutomatic (manager restores)Manual (onSaveInstanceState)
Deep LinksVia Navigation ComponentNative support via intent-filter

Jetpack Fragment and Jetpack Navigation

The modern approach to working with Fragment is Jetpack Navigation Component, which replaces manual FragmentManager management. The library provides NavGraph (XML navigation graph), NavHostFragment, and Safe Args for type-safe data transfer.

Jetpack Fragment library (androidx.fragment:fragment-ktx) includes FragmentResult API, DialogFragment, BottomSheetDialogFragment, and integration with Lifecycle-aware components. Since 2026, Google recommends using Fragment only through Jetpack Navigation, not directly.

xml

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@+id/listFragment">

    <fragment
        android:id="@+id/listFragment"
        android:name=".ListFragment"
        android:label="List">
        <action
            android:id="@+id/action_list_to_detail"
            app:destination="@+id/detailFragment" />
    </fragment>

    <fragment
        android:id="@+id/detailFragment"
        android:name=".DetailFragment"
        android:label="Details" />
</navigation>

Frequently Asked Questions

What is FragmentManager?

FragmentManager is a class that manages fragment transactions. It adds, removes, and replaces fragments in an Activity container. FragmentManager restores fragment state upon Activity recreation and manages the back stack.

How is Fragment different from Activity?

Fragment is a part of UI inside an Activity, it cannot exist independently. Fragment survives Activity recreation on screen rotation. Activity is a full screen with its own Lifecycle, Fragment depends on Activity's Lifecycle.

When to use Fragment instead of Activity?

Fragment — when a screen consists of several independent blocks (tabs, master-detail, tablet adaptation). Activity — when a screen has no repeating blocks. Google recommends Single Activity + multiple Fragment.

How to transfer data between Fragments?

Three ways: through the parent Activity (shared ViewModel), through Fragment Result API (setFragmentResult), through Bundle arguments when creating a Fragment. ViewModel is the preferred method as data is preserved during recreation.

What is Fragment Transaction?

Fragment Transaction is an atomic operation that changes the fragment set. FragmentManager.beginTransaction() opens a transaction where you can call add, remove, replace, hide, show. Each transaction ends with commit() or commitNow().

Summary

  • Fragment is a reusable UI component inside an Activity with its own lifecycle, layout, and state
  • FragmentManager manages fragment transactions and restores their state upon Activity recreation
  • FragmentTransaction is an atomic operation for adding, replacing, removing, and hiding fragments
  • Fragment lifecycle includes six callbacks, from onAttach to onDetach, with an additional onCreateView point
  • ViewModel is the recommended way to exchange data between fragments in one Activity
  • Fragment Result API provides type-safe one-time event transfer between fragments

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also