A Fragment is a reusable portion of UI with its own lifecycle, hosted inside an Activity. Fragments let you build flexible layouts — especially for tablets (master/detail) and single-pane phones (swap screens in one activity).
Fragment vs Activity: An Activity owns the window; a Fragment owns a slice of that window. Multiple fragments can live in one activity, and each fragment can be added, removed, or replaced independently.
Adaptive layouts — show two fragments side-by-side on tablets, one at a time on phones
Back stack — navigate between screens without launching new activities
Works with Jetpack Navigation, ViewPager2, and Bottom Navigation
Fragment Lifecycle States
[Fragment created]
↓
onAttach() → Fragment linked to host Activity
↓
onCreate() → Initialize non-UI resources
↓
onCreateView() → Inflate layout (return View)
↓
onViewCreated() → Setup views, listeners, observers
↓
onStart() → Fragment visible (not yet interactive)
↓
onResume() → Fragment active and interactive
↓
[User navigates away / fragment hidden]
↓
onPause() → onStop() → onDestroyView() → onDestroy() → onDetach()
Back stack note:
replace() + addToBackStack() → Back button reverses transaction
without addToBackStack() → Back exits the Activity
Key Lifecycle Callbacks
Callback
When Called
Typical Use
onAttach()
Fragment associated with Activity
Get Activity reference (prefer requireContext() later)
onCreate()
Fragment instance created
Read arguments, init ViewModel
onCreateView()
Build UI
Inflate layout, return root View
onViewCreated()
View hierarchy ready
Find views, set click listeners, observe LiveData
onDestroyView()
View being destroyed
Clear view references to avoid memory leaks
onDetach()
Fragment unlinked from Activity
Final cleanup
Logging the Fragment Lifecycle
Kotlin — HomeFragment.ktclass HomeFragment : Fragment(R.layout.fragment_home) {
private val TAG = "HomeFragment"
override fun onAttach(context: Context) {
super.onAttach(context)
Log.d(TAG, "onAttach")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated")
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
}
override fun onPause() {
Log.d(TAG, "onPause")
super.onPause()
}
override fun onDestroyView() {
Log.d(TAG, "onDestroyView")
super.onDestroyView()
}
}
2Creating Fragments
Modern Android uses the AndroidX Fragment class from androidx.fragment:fragment-ktx. You create a Kotlin class, a layout XML file, and host it in an Activity container.
A FragmentTransaction is a set of changes (add, replace, remove, hide, show) applied atomically. You obtain it from supportFragmentManager (Activity) or parentFragmentManager (Fragment).
The Jetpack Navigation Component simplifies fragment navigation with a visual graph, type-safe arguments, deep links, and automatic Up/Back handling via NavController.
XML — activity_main.xml with NavHost<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
Navigate with NavController
Kotlin — Inside HomeFragmentoverride fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = findNavController()
view.findViewById<Button>(R.id.btnGoProfile).setOnClickListener {
val action = HomeFragmentDirections.actionHomeToProfile(userId = "user_42")
navController.navigate(action)
}
}
// Safe Args generated class passes typed arguments automatically
Setup ActionBar / Toolbar with NavController
Kotlin — MainActivity.ktclass MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
setupActionBarWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
5Bottom Navigation
Bottom Navigation displays 3–5 top-level destinations at the bottom of the screen. It pairs naturally with the Navigation Component — each menu item maps to a destination in your nav graph.
Tip: Menu item IDs must match fragment destination IDs in nav_graph.xml. Use app:popUpTo and app:popUpToSaveState on bottom-nav destinations to preserve each tab's state when switching.
Preserve tab state in nav graph
XML — Bottom nav destination options<fragment
android:id="@+id/homeFragment"
android:name="com.example.app.HomeFragment"
android:label="Home"
app:popUpTo="@id/nav_graph"
app:popUpToSaveState="true"
app:launchSingleTop="true"
app:restoreState="true" />
6Drawer Navigation
A Navigation Drawer slides in from the left edge and exposes many destinations without cluttering the main UI. Use DrawerLayout + NavigationView with the Navigation Component for seamless integration.
Kotlin — MainActivity.kt (Drawer setup)class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
val navView = findViewById<NavigationView>(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(
setOf(R.id.homeFragment, R.id.settingsFragment, R.id.aboutFragment),
drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
Bottom Nav vs Drawer — when to use which
Pattern
Best For
Max Destinations
Bottom Navigation
Primary app sections users switch between often
3–5 items
Navigation Drawer
Many destinations, settings, secondary screens
5+ items
Combined
Bottom nav for main tabs + drawer for settings/about
Flexible
7Hands-On Exercises
1
Create a single-Activity app with two fragments: HomeFragment and ProfileFragment. Use a button in Home to navigate to Profile with replace() and addToBackStack(). Press Back to return.
2
Add Log statements to every lifecycle method in both fragments. Switch between them and observe the callback order in Logcat.
3
Pass a username from Home to Profile using a Bundle argument. Display it in a TextView on the Profile screen.
4
Refactor the app to use the Navigation Component: create nav_graph.xml, add a NavHostFragment, and navigate with findNavController().navigate().
5
Add a Bottom Navigation bar with three tabs (Home, Search, Profile). Wire it to the nav graph using setupWithNavController().
6
Replace Bottom Navigation with a Navigation Drawer. Add a MaterialToolbar with hamburger icon, header layout, and drawer menu items for Home, Settings, and About.
7
Bonus: Combine Bottom Navigation (3 main tabs) with a Drawer (Settings + Logout). Ensure the Up button and Back button behave correctly on nested screens.
Fragments & Navigation MCQ Practice
10 Basic MCQs10 Advanced MCQs
10 Basic Fragments & Navigation MCQs
1
Fragment represents?
AReusable UI portion in an Activity
BBackground service
CDatabase table
DGradle module
Explanation: Fragments modularize UI hosted by FragmentActivity/AppCompatActivity.
2
FragmentManager handles?
AAdding/replacing Fragments
BAPK signing
CSDK download
DLint only
Explanation: FragmentManager executes transactions and back stack.
3
Jetpack Navigation uses?
ANavController and nav graph XML
BOnly manual FragmentTransaction
CADB
DWear OS
Explanation: Navigation Component defines destinations and actions in a graph.
4
BottomNavigationView typically switches?
ATop-level destinations / tabs
BGradle variants
CKernel modules
DPermissions only
Explanation: Bottom nav maps menu items to nav graph destinations.
5
onCreateView in Fragment returns?
ARoot View of fragment layout
BIntent
CService binder
DGradle config
Explanation: Inflates layout and returns the fragment's view hierarchy.
6
NavHostFragment role?
AContainer hosting NavController graph
BLauncher icon
CDatabase helper
DProGuard
Explanation: NavHostFragment is the swap container for destinations.
7
DrawerLayout often pairs with?
ANavigationView for side menu
BRecyclerView only
CSQLite
DCameraX
Explanation: Material drawer uses NavigationView + AppBarConfiguration.
8
Fragment lifecycle tied to?
AHosting Activity lifecycle
BLinux kernel only
CPlay Store
DIndependent always
Explanation: Fragment callbacks interleave with Activity (onStart, onResume, etc.).
9
Safe Args plugin provides?
AType-safe navigation arguments
BFaster emulator
CAuto screenshots
DFree hosting
Explanation: Safe Args generates Directions classes for nav arguments.
10
replace() vs add() in transaction?
Areplace removes container fragment; add stacks
BIdentical
COnly add legal
DNeither works
Explanation: replace swaps current; add can stack multiple in same container.
10 Advanced Fragments & Navigation MCQs
11
onDestroyView Fragment should?
ANull out view binding references
BStart new Activity always
CSkip super
DCommit retained fragment
Explanation: Views destroyed on destroyView — clear binding to prevent leaks.
12
popBackStack()?
APops Fragment transactions from back stack
BUninstalls app
CClears Logcat
DRevokes permission
Explanation: addToBackStack enables reverse navigation via Back.
13
Single-Activity architecture means?
AOne Activity hosts multiple Fragments
BOne Fragment total
CNo nav graph
DNo ViewModel
Explanation: Navigation moves between fragments inside one Activity shell.
14
Deep links in nav graph?
AdeepLink attribute on destination
BOnly implicit intents banned
CGradle task
Dstrings.xml
Explanation: Nav graph can declare URI patterns matched by NavController.
15
Fragment result API used for?
AParent-child fragment communication
BPlay billing
CDex merging
DHAL access
Explanation: setFragmentResult delivers bundles to listeners in same Activity.
16
ViewPager2 with Fragments uses?
AFragmentStateAdapter
BArrayAdapter
CCursorAdapter
DServiceConnection
Explanation: FragmentStateAdapter supplies Fragments for each page.
17
Navigation UI setupWithNavController?
AWires BottomNav/Toolbar to NavController
BStarts emulator
CMerges manifest
DRuns lint
Explanation: Automatically handles destination selection and Up button.
18
Retained Fragment (deprecated pattern)?
ASurvived rotation before ViewModel
BNever existed
CSame as Service
DReplaces NavHost
Explanation: ViewModel now preferred for surviving config changes.
19
Multiple back stacks Bottom Nav (Navigation 2.4+)?
Asave/restore state per tab
BImpossible
CRequires separate apps
DADB only
Explanation: Navigation supports independent back stacks for each top-level tab.
20
DialogFragment advantage?
ALifecycle-aware modal UI
BFaster RecyclerView
CNative HAL
DReplaces SQLite
Explanation: DialogFragment handles config changes and FragmentManager properly.
Click an option to select, then check answers.
Fragments & Navigation Interview Q&A
15 topic-focused questions for interviews and revision.
1Why use Fragments instead of many Activities?medium
Answer: Reuse UI on phones/tablets, share ViewModels, single-Activity nav, bottom tabs without Activity overhead.
2Explain Fragment lifecycle vs Activity.medium
Answer: Fragment has onAttach, onCreate, onCreateView, onViewCreated, onDestroyView — view can be destroyed while fragment instance exists.
3What is a FragmentTransaction?easy
Answer: Atomic set of operations (add/replace/hide) committed to FragmentManager; optional back stack entry.
4How does Jetpack Navigation simplify navigation?medium
Answer: Central nav graph, type-safe args, deep links, animations, and NavController handles back stack consistently.
5Setup Bottom Navigation with Navigation Component.medium
Answer: Menu items match destination IDs; NavHost in layout; setupWithNavController connects BottomNavigationView.
6Implement Navigation Drawer steps.medium
Answer: DrawerLayout + NavigationView; AppBarConfiguration with drawer destinations; NavigationUI.setupWithNavController.
7When to use addToBackStack?easy
Answer: When user should press Back to undo fragment transaction (e.g., master-detail drill-down).
8Common Fragment crash: not attached to context.hard
Answer: Access context after onDetach; use viewLifecycleOwner, requireContext() only when attached, or lifecycle-aware observers.
9Difference between child FragmentManager and parent.hard
Answer: Child FM manages nested fragments inside a parent fragment; use getChildFragmentManager for nested cases.
10What is Safe Args?medium
Answer: Gradle plugin generating Kotlin/Java classes for nav arguments — compile-time safety vs raw bundles.