0% found this document useful (0 votes)
3 views

Week_6_Fragment

The document provides an overview of using Fragments in Android for mobile application development, emphasizing their role in creating dynamic and flexible user interfaces. It covers the lifecycle of Fragments, how to create and manage them, as well as techniques for fragment navigation and communication between Fragments and Activities. Key concepts include Fragment transactions, adding/removing Fragments at runtime, and using Navigation Architecture Components for managing navigation within an app.

Uploaded by

sarahayeesha1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Week_6_Fragment

The document provides an overview of using Fragments in Android for mobile application development, emphasizing their role in creating dynamic and flexible user interfaces. It covers the lifecycle of Fragments, how to create and manage them, as well as techniques for fragment navigation and communication between Fragments and Activities. Key concepts include Fragment transactions, adding/removing Fragments at runtime, and using Navigation Architecture Components for managing navigation within an app.

Uploaded by

sarahayeesha1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Week 6:

Fragment
(EXAM)
CET3013: MOBILE APPLICATION DEVELOPMENT
Today's lecture 2 ui combine into 1 interface called fragment

To add in the fragment  use fragment


transaction
• Introduction of Fragment
• Creating a Fragment 1st UI

• Building a Flexible UI
• Communicating with Other
Fragments
• Fragment navigation 2nd UI

Cannot simply add in, Need to have place holder to


add in the fragment, either one:
1. Fragment
2. Framelayout
3. FragmentContainerView (the most
recommended)
Introduction

• To create a dynamic and multi-pane user interface on


Android, you need to encapsulate UI components and
activity behaviours into modules that you can swap into
and out of your activities.

• You can create these modules with the Fragment class,


which behaves somewhat like a nested activity that can
define its own layout and manage its own lifecycle.
Fragment Spilt to different part UI

• An activity is a container for views

• When you have a larger screen device than a phone –like a


tablet it can look too simple to use phone interface here.

• Fragments
• Mini-activities, each with its own set of views
• One or more fragments can be embedded in an Activity
• You can do this dynamically as a function of the device type (tablet or not)
or orientation
Fragment Idea

Fragments
• Mini-activities, each with its own set of views
• One or more fragments can be embedded in an Activity
• You can do this dynamically as a function of the device type (tablet or not)
or orientation

You might
detail decide to run

a tablet in
Master  portrait mode
with the handset
model of only
one fragment
in an Activity
Fragment

• A Fragment represents a behavior or a portion of user interface


in an Activity.

• You can combine multiple fragments in a single activity to build


a multi-pane UI and reuse a fragment in multiple activities.

• You can think of a fragment as a modular section of an activity,


which has its own lifecycle, receives its own input events, and
which you can add or remove while the activity is running (sort
of like a "sub activity" that you can reuse in different activities).
Fragment Lifecycle

• Fragment in an Activity---Activity Lifecyle influences


• Activity paused  all its fragments paused
• Activity destroyed  all its fragments paused
• Activity running  manipulate each fragment
independently.
A object to manipulate the fragment
• Fragment transaction add, remove, etc. (these all are
manipulate)
• adds it to a back stack that's managed by the activity—each
back stack entry in the activity is a record of the fragment
transaction that occurred.
• The back stack allows the user to reverse a fragment
transaction (navigate backwards), by pressing the Back button.
Add the fragment on the top of another fragment 重疊
Creating a Fragment

• You can think of a fragment as a modular section of an


activity, which has its own lifecycle, receives its own
input events, and which you can add or remove while
the activity is running (sort of like a "sub activity" that
you can reuse in different activities).
Create a Fragment Class
To create a fragment, extend the Fragment class, then override key lifecycle
methods to insert your app logic, similar to the way you would with an Activity
class.
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class FragmentOne : Fragment() { Extend class into fragment (also have use binding)
private var _binding: FragmentTextBinding? = null
private val binding get() = _binding!!

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
_binding = FragmentTextBinding.inflate(inflater, container, false)
return binding.root
}
}
Create a Fragment Class
• While fragments are reusable, modular UI components, each instance of a
Fragment class must be associated with a parent FragmentActivity. You can achieve
this association by defining each fragment within your activity layout XML file.
Add a Fragment to an Activity using XML
Building a Flexible UI

• When designing your application to support a wide range of screen sizes,


you can reuse your fragments in different layout configurations to optimize
the user experience based on the available screen space.
Add a Fragment to an Activity at Runtime
• Rather than defining the fragments for an activity in the layout file—as
shown in the previous lesson with the <fragment> element—you can add a
fragment to the activity during the activity runtime. This is necessary if you
plan to change fragments during the life of the activity.
• To perform a transaction such as add or remove a fragment, you must use
the FragmentManager to create a FragmentTransaction, which provides APIs
to add, remove, replace, and perform other fragment transactions.
• If your activity allows the fragments to be removed and replaced, you should
add the initial fragment(s) to the activity during the activity's onCreate()
method.
• An important rule when dealing with fragments—especially when adding
fragments at runtime—is that your activity layout must include a container
View in which you can insert the fragment.
Adding and Managing
Fragment Sequence Steps
1. Create an instance of the fragment’s class.
2. Pass any additional intent arguments through to the class
instance.
3. Obtain a reference to the fragment manager instance.
4. Call the beginTransaction() method on the fragment manager
instance. This returns a fragment transaction instance.
5. Call the add() method of the fragment transaction instance,
passing through as arguments the resource ID of the view that is
to contain the fragment and the fragment class instance.
6. Call the commit() method of the fragment transaction.
Create the transaction
Then only can start to add in the fragment
Example: Adding Fragment
Dynamically

Add to: location and fragment

* Step 3 to Step 6 can be abbreviated into a single line


Replace One Fragment with Another

• The procedure to replace a fragment is similar to adding one,


but requires the replace() method instead of add().

• Keep in mind that when you perform fragment transactions,


such as replace or remove one, it's often appropriate to allow
the user to navigate backward and "undo" the change. To allow
the user to navigate backward through the fragment
transactions, you must call addToBackStack() before you
commit the FragmentTransaction.

If use addToBackStack(), then if have a fragment and b fragment, the


2nd add in fragment will on the top of 1st fragment
Example: Replacing Fragment
Dynamically
Communicating with Other Fragments

• In order to reuse the Fragment UI components, you should


build each as a completely self-contained, modular component
that defines its own layout and behavior. Once you have
defined these reusable Fragments, you can associate them
with an Activity and connect them with the application logic to
realize the overall composite UI.

2 fragment will communicate using interface


When click on left hand side, the right hand side (blue color) will change
Define an Interface

• To allow a Fragment to communicate up to its Activity, you can define an


interface in the Fragment class and implement it within the Activity. The
Fragment captures the interface implementation during its onAttach()
lifecycle method and can then call the Interface methods in order to
communicate with the Activity.
Override onAttach Method
MainActivity: Implements
Fragment Interface
Fragment Navigation
•Very few Android apps today consist of just a single screen.
•In reality, most apps comprise multiple screens through which
the user navigates using screen gestures, button clicks and
menu selections.
Fragment Navigation
•The fragment navigation is handled by a navigation controller
which is represented by the NavController class.
•Navigation Architecture Component is a straightforward
process involving a navigation host, navigation graph, navigation
actions and a minimal amount of code writing to obtain a
reference to, and interact with, the navigation controller instance.
Navigation Host
•A navigation host is simply a special fragment (NavHostFragment)
that is embedded into the user interface layout of an activity and
serves as a placeholder for the destinations through which the
user will navigate.
Navigation Host Layout File

The points of note in the above navigation host fragment element are the reference to the
NavHostFragment in the name property, the setting of defaultNavHost to true and the
assignment of the file containing the navigation graph to the navGraph property.
Navigation Graph
•The navigation graph holds all of the navigation-related
information that your app requires, and describes the
possible paths the user can take when navigating the app.
Navigation Controller
•The navigation controller controls which fragment is displayed
in the navigation host as the user navigates through the app.
Navigation Configuration
•You need to add a library dependency to the app’s version
of the build.gradle file.
Navigation Action
•Actions are used to connect destinations in the navigation
graph, and they define possible paths the user can take when
navigating through the app.
•Every action must have a unique ID. Android uses this ID to
determine which destination needs to be displayed as the
user navigates through the app.
Navigation Action
Navigation Graphs XML
Navigation Action: Passing
Arguments
•Data may be passed from one destination to another during
a navigation action by making use of arguments.
•An argument consists of a name, type and an optional
default value and may be added manually within the XML.
•A navigation action is triggered by calling the controller’s
navigate() method and passing through the resource id
Navigation Action: Passing
Arguments
Navigation Action: Passing
Arguments
Navigation Action: Safe Args
•The Navigation component that lets you pass arguments to
destinations in a type-safe way.
•We need to update the project and app build.gradle files.

You might also like