Fragments and Navigation
Fragments and Navigation
MOBILE APPLICATION
DEVELOPMENT
FRAGMENTS AND NAVIGATION
Created and Updated by S. Ong
Adapted by Chiew T K
Semester 1, 2024/2025
QUICK QUESTION 1
Can you give an example of
Common Layout (Viewgroup)
and Layout using Adapter?
OUTLINE
• Fragment
• Fragment Modularity
• Fragment Creation
• Fragment Base Class Variation
• Add Fragment to Activity
• Fragment Manager
• Fragment Transaction
• Fragment Lifecycle
• Navigation
• Navigation Principles
[email protected]
RECALL What is the
ACTIVITY activity?
FRAGMENT
• A fragment is a section in
your UI design, that is meant
to allow reusability and
enhance flexibility in a
mobile application.
• Fragment introduces
modularity into the activity’s
UI by allowing us to divide UI
into discrete chunks/sections.
FRAGMENT
MODULARITY
• Consider an app that
responds to
various screen
sizes:
• On larger
screens, the app
should display a
static navigation
drawer and a list in
a grid layout.
• On smaller
screens, the app
Sample scenario from Android Documentation
should display a
bottom navigation
bar and a list in a
[email protected]
linear layout.
7
FRAGMENT
MODULARITY
• Managing all of these
variations in the activity
can be unwieldy.
• Separating the
navigation elements
from the content can
make this process more
manageable.
• The activity is then
responsible for
displaying the correct
navigation UI while the
Sample scenario from Android Documentation
fragment displays the
list with the proper
One example scenario of using a Fragment
layout.
FRAGMENT
MODULARITY
ENHANCE FLEXIBILITY
• Dividing the UI into sections (or, fragments in this
case) makes it easier to modify the UI appearance at
runtime
• Appearance – the visibility of each fragment can be
turned on / turned off, or added/removed/replaced
during the runtime
• The appearance history can be added to the back state
of activity and allow the changes to be reversed when
needed.
• Avoid switching activities when different appearances
are needed for different configurations or settings.
FRAGMENT
MODULARITY
ENHANCE REUSABILITY
• A fragment can be designed
in a standalone manner.
• And it can be reused to carry
different information in a
single activity depending on
the data sent to the fragment
class.
• Or, it can also be reused in
multiple activities to leverage
the fragment’s UI.
• Reduce layout XML
redundancy.
FRAGMENT CREATION
• A fragment has its own lifecycle BUT must be
contained inside an activity.
• One activity can have multiple fragments.
• One parent fragment can have child fragment.
FRAGMENT CREATION
• Fragments require a dependency on the AndroidX
Fragment library. You need to add the
Google Maven repository to your
project's settings.gradle file in order to include this
dependency.
FRAGMENT CREATION
• Extend AndroidX Fragment class, and override its
methods to insert the app logic
• Similar to the activity class, but the activity class
extends AppCompatActivity.
• Make sure to provide the fragment’s layout resource
to the base constructor.
FRAGMENT CREATION
• You can also
create Fragment
by using Android
Studio
• A similar way
to create a new
activity.
FRAGMENT BASE
CLASS VARIATION
• DialogFragment
• To create a fragment to display a floating
dialog.
• An alternative solution to the dialog
helper method in the Activity class.
• Extra reading:
https://developer.android.com/guide/frag
ments/dialogs
• PreferenceFragment
• Display a hierarchy of Preference objects
in a list.
• To create a setting screen for your mobile
app.
• Extra reading:
https://developer.android.com/develop/ui/
views/components/settings
[email protected]
15
16
ADD FRAGMENT TO
ACTIVITY
• Two methods:
• Method 1: Defining the fragment in the activity’s XML
layout file.
• Method 2: Defining an empty container in the activity’s
XML layout file, then programmatically adding the
fragment during the runtime.
• Both methods need to add a FragmentContainerView
• Placeholder to hold the fragment.
• A better alternative to FrameLayout and other
viewgroups because it contains specific fixes to
Fragment.
• A similar idea of using the ImageView to hold images.
ADD FRAGMENT TO
ACTIVITY
METHOD 1
• Method 1: Defining the fragment in the activity’s XML
layout file.
ADD FRAGMENT TO
ACTIVITY
METHOD 1
• Method 1: Defining the fragment in the activity’s XML
layout file.
ADD FRAGMENT TO
ACTIVITY
METHOD 2
• Method 2: Defining an empty container in the
activity’s XML layout file, then programmatically
adding the fragment during the runtime.
ADD FRAGMENT TO
ACTIVITY
METHOD 2
• Method 2: Defining an empty container in the
activity’s XML layout file, then programmatically
adding the fragment during the runtime.
ADD FRAGMENT TO
ACTIVITY
METHOD 2
• Unlike the XML approach, the android:name attribute isn't used
on the FragmentContainerView. So no specific fragment is
automatically instantiated.
• Instead, a FragmentTransaction is used to instantiate a fragment
and add it to the activity's layout.
• While your activity is running, you can make fragment
transactions such as adding, removing, or replacing a fragment.
• In your FragmentActivity, you can get an instance of the
FragmentManager, which can be used to create
a FragmentTransaction.
• Then, you can instantiate your fragment within your
activity's onCreate() method using FragmentTransaction.add(),
passing in the ViewGroup ID of the container in your layout and
the fragment class you want to add and then commit the
transaction,
[email protected]
22
FRAGMENT MANAGER
• Class responsible for performing actions on your
app's fragments, such as adding, removing, or
replacing them, and adding them to the back stack.
• Every FragmentActivity and subclasses thereof, such
as AppCompatActivity, have access to
the FragmentManager through the
getSupportFragmentManager() method.
FRAGMENT TRANSACTION
• FragmentManager can add, remove and/or replace a
fragment during the runtime.
• These set of changes applied (or committed) to the
fragment is called a FragmentTransaction.
• To add a fragment to FragmentManager
• Use add() on the transaction
• To remove a fragment from the host activity
• Use remove() and specify the fragment using
findFragmentbyId() or findFragmentbyTag()
FRAGMENT TRANSACTION
• To replace an existing fragment with an instance of a
new fragment
• Use replace() (equivalent to remove() + add())
• To show and hide the view of the fragment that has
already been added to the container
• Use show() and hide()
• Set the visibility of the fragment without affecting its
lifecycle.
• To temporarily remove the fragment from the view
hierarchy (moved to STOPPED state)
• Use detach(), can attach() when want to use it back
• Differs with remove() – in DESTROYED state
FRAGMENT LIFECYCLE
• Each fragment has its own lifecycle
• Implements lifecycleOwner that constains 5 lifecycle
states:
• Initialized
• Created
• Started
• Resumed
• Destroyed
• Include several callback methods:
• onCreate(), onStart(), onResume(), onPause(), onStop()
and onDestroy()
FRAGMENT LIFECYCLE
• Apart from Fragment lifecycle, each fragment that is
existed also has another independent lifecycle, called
as Fragment View Lifecycle.
• Having access to the view's Lifecycle is useful for
situations where a Lifecycle-aware component should
only perform work while a fragment's view exists,
such as observing LiveData that is only meant to be
displayed on the screen.
[email protected]
FRAGMENT
LIFECYCLE,
CALLBACKS
AND VIEW
LIFECYCLE
27
[email protected]
28
FRAGMENT
INITIALIZED
• When a fragment is instantiated, it begins in
the INITIALIZED state.
• For a fragment to transition through the rest of its
lifecycle, it must be added to a FragmentManager.
The FragmentManager is responsible for determining
what state its fragment should be in and then moving
them into that state.
FRAGMENT CREATED
• Fragment has been added
to the FragmentManager
and the onAttach() method
has been called.
• Can restore state that
associated with the
fragment.
• Invoke onCreate() that
received
savedInstanceState (to
retrieve any Bundle
argument saved in previous
state)
[email protected]
30
FRAGMENT CREATED
AND VIEW INITIALIZED
• Fragment view is created
when it contains valid View
instance (fragment is
inflated).
• Appropriate place to set up
the initial state of your view:
• to start observing LiveData
instances whose callbacks
update the fragment's view
• to set up adapters on
any viewgroup instances in
your fragment's view.
FRAGMENT DESTROYED
(DOWNWARD STATE TRANSITION)
NAVIGATION
Navigation refers to the interactions that allow users to navigate
across, into, and back out from the different pieces of content
within your app.
39
NAVIGATION
PRINCIPLES
• Smooth navigation
is important to user
experience.
• There are a few
navigation
principles
recommended by
Android
Documentation to
enable a great
navigation
experience while
the user is using
your mobile app.
NAVIGATION PRINCIPLE
FIXED START DESTINATION
• Every app has ONE fixed start destination.
• The first screen that the user will see.
• Not including the sign-up or registration screen that
users might see for the first time only – also called as
conditional screen.
• Also should be the last screen to see when users
press the back button.
NAVIGATION PRINCIPLE
NAVIGATION BACK STACK
• The navigation state should keep the back stacks of
your navigation.
• The top on the back stack should be your current
screen.
• The bottom on the back stack should be the fixed
start destination.
• Uses the pop and push idea when managing the
navigation back stack
NAVIGATION PRINCIPLE
IDENTICAL UP AND BACK
BUTTONS
• Back button is located at the system navigation bar.
• used to navigate in reverse-chronological order
through the history of screens the user has recently
worked with.
• Up button is located at the App Bar at the top of the
screen.
• These two buttons should behave in an identical
manner.
NAVIGATION PRINCIPLE
UP BUTTON NEVER EXIT
• The up button shouldn’t exist when it’s on the start
destination of the app.
• The up button appears when it’s navigated away
from the start destination.
• The up button should never exit the mobile app.
• But the back button can.
HOW TO CREATE
NAVIGATION?
• Manually using Listener/action.
• Or, using Navigation Editor to create Navigation
Graph
• For Android 3.3 and above only.
• Let’s learn how to do it in Practical 6.
QUICK QUESTION 2
What is the difference
between activity and
fragment?
FURTHER READING
• Transition Animation for Fragment
• https://developer.android.com/guide/fragments/animat
e
• Single Activity – Why, When and How
• https://www.youtube.com/watch?v=2k8x8V77CrU
• Fragment: Past, Present and Future
• https://www.youtube.com/watch?v=RS1IACnZLy4