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 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.
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 Callback | Activity Equivalent | Purpose |
|---|---|---|
| onAttach | before onCreate | Fragment attached to Activity |
| onCreate | onCreate | Initialization of non-UI data |
| onCreateView | onCreate | Creating layout via inflater |
| onViewCreated | onCreate | Binding UI elements after view creation |
| onDestroyView | onDestroy | Removing view, releasing UI resources |
| onDetach | onDestroy | Fragment detached from Activity |
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 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).
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.
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.
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.
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.
// 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.
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.
| Criterion | Fragment | Activity |
|---|---|---|
| Creation speed | Faster (lightweight component) | Slower (system process) |
| Reusability | High (one fragment in different Activities) | Low (each screen has its own Activity) |
| Transition animation | Flexible (FragmentTransaction) | Limited (overridePendingTransition) |
| Preservation on rotation | Automatic (manager restores) | Manual (onSaveInstanceState) |
| Deep Links | Via Navigation Component | Native support via intent-filter |
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.
<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
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.
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.
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.
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.
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
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.
Read also