Android / Kotlin:
Intro to Fragments
Week 13
Lecture
Dr. Volodymyr Voytenko
Outline
Fragment key features and fragment
behavior
Fragment life-cycle and specific methods
Adding / replacing fragments at run-time
Fragment Case Study
Individual Assignment
The need for UI flexibility
Smartphone Tablet
We need the ability to compose/recompose an activity's view at run-time
depending on what the user or the device requires
Fragment key features
Figure 1. An example of how two UI modules defined by fragments can be
combined into one activity for a tablet design, but separated for a handset
design [Source: http://developer.android.com/]
Why Fragments ?
1. Dealing with device form-
factor differences
2. User interface
organization
3. Advanced UI metaphors
4. Passing information
between app screens
Why Fragments ?, cont.
1. Dealing with device form-factor
differences
- The form factor of a mobile phone is its size, shape,
and style, as well as the layout and position of its
major components.
- A separate Fragment can be created for each form
factor with the specific UI details
- Fragments eliminate problem by taking on the UI
details
- The Activity is then free to delegate the UI
responsibility to the appropriate Fragment for the
Why Fragments ?, cont. 2
2. User interface organization
Two of the most common UI
metaphors for organizing
application screens are Tabs and
Dropdown Lists.
Fragments make implementing
these UI metaphors easy. In both
cases we need Android ActionBar
into the appropriate navigation
mode, implement the appropriate
interface, and then use a
FragmentTransaction to switch
between the currently displayed
Fragments.
Why Fragments ?, cont. 3
3. Advanced UI
metaphors
As the use of Fragments
matures, they are an
increasingly important part
of rich UI design and are
becoming the foundation of
some of the more advanced
UI metaphors.
To add swipe navigation to an app, we can implement a Fragment for each
screen, place a ViewPager in the UI layout and connect the ViewPager to a
FragmentPagerAdapter.
Why Fragments ?, cont. 4
4. Passing information between app screens
If each screen in an Android app implemented as a separate Activity, it
creates a challenge in passing information between screens because
the Android Intent mechanism does not allow passing a reference type
(i.e. object) directly between Activities. Instead the object must be
serialized or a globally accessible reference made available.
By making each UI screen a separate
Fragment, this problem may be
solved: fragments always exist within
the context of a given Activity and
can always access that Activity. By
storing the information of interest
within the Activity, the Fragment for
each screen can easy access the
object reference through the Activity.
How Fragment is different
from an Activity?
Fragment behavior
A fragment is usually used as part of an activity's user
interface and contributes its own layout to the activity.
It has most functions of an Activity, but it is not an
Activity:
- Multiple Fragments can be combined in a single
activity in which the fragments can be created,
removed dynamically
- A fragment has its own lifecycle.
- A fragment must always be embedded in an Activity
and the fragment’s lifecycle is directly affected by the
host activity’s lifecycle.
- If fragment stack is not empty, pressing Back button
navigates the user to the latest fragment in the same
activity, not the prior activity.
Fragment lifecycle
Yes, Fragments have their own life
cycles!
But Fragment lifecycle also interacts
with containing Activity lifecycle, e.q.:
- when Activity pauses, its Fragments
are paused as well;
- when Activity destroys, its
Fragments are destroyed.
Fragment Lifecycle States
Fragment LifeCycle Callback
Fragment LifeCycle Callback, cont.
Fragment Lifecycle summary
Fragment vs. Activity Lifecycle
How to create a Fragment ?
Creating a Fragment
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.
One difference when creating a Fragment is that you must use the
onCreateView() callback to define the layout. In fact, this is the
only callback you need in order to get a fragment running with its
own layout:
class ExampleFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false)
}
}
*Just like an activity, a fragment should implement other lifecycle callbacks that allow you to manage
its state as it is added or removed from the activity and as the activity transitions between its lifecycle
states.
Layout for fragments
ExampleFragment.kt
example_fragment.xml
Adding Fragment to Activity
There is a static way to add a fragment to the activity layout:
•Declare the fragment inside the activity's layout file. In this case,
you can specify layout properties for the fragment as if it were a view.
For example, here's the layout file for an activity with two fragments:
Adding/replacing
fragments at run-time
Fragment Manager
Each Activity has its own Fragment Manager accessible through
getFragmentManager() or getSupportFragmentManager(). It maintains references to all
fragments inside Activity. Use findFragmentById() or findFragmentByTag() to get
reference to a specific fragment, and add/replace it in the program.
https://developer.android.com/guide/components/
Fragment Transaction
Changes to the UI in terms of adding, removing and replacing Fragments are
conducted using FragmentTransaction:
Begin a transaction
<Add, remove, replace whatever fragments you want>
Commit the transaction
https://developer.android.com/guide/components/
Fragment Transaction Example
For example, here's how you can replace one fragment with
another, and preserve the previous state in the back stack.
Here, we replaced a fragment using the replace() method,
specifying the fragment to add and the view in which to insert
it.
In this example, newFragment replaces whatever fragment (if any) is currently in the layout container identified by the R.id.fragment_container ID
Each transaction is a set of changes that you want to perform at the
same time. You can set up all the changes you want to perform for a
given transaction using methods such as add(), remove(), and
replace(). Then, to apply the transaction to the activity, you must
call commit().
Why do you need to call addToBackStack() before commit transaction?
https://developer.android.com/guide/components/fragments
Case Study
Build an app to display two static Fragments within Activity
“Android first fragment demo”
Check video instructions on-line for this tutorial to start
Once completed, move to individual assignment next two
slides to make fragment switch dynamically
Fragment 2 Fragment 1
Individual Assignment
1)Add your name and student
“Dynamic ID to
fragment theapp”
switch app bar;
2)Add two buttons on the top of layout to switch between
fragments dynamically as shown below – use different
background colors and the picture for each fragments as
shown
background
background
textview picture
3) continue
Fragment 1 Fragment 2
Individual Assignment
“Dynamic fragment switch app”- continue
3) Add a hiding of a fragments content and clear background
upon clicking on its own widgets (textview on Fragment 1 and
image on Fragment 2)
Clickable
image
Clickable
textview
Fragment 1 Fragment 2
4) Submit zip-project on-line with your reelections and
screenshots
References
Meier, R. 2010. Professional Android 2 Application Development.
Indianapolis: Wiley. ISBN-10: 0470565527 ISBN-13: 9780470565520
Jim Wilson, “4 reasons to use Android Fragments “,
https://www.pluralsight.com/blog/software-development/android-fragments
http://simpledeveloper.com/how-to-communicate-between-fragments-and-
activities/
Bruce Scharlau, Mobile Computing, University of Aberdeen, 2011
ANDROID PROGRAMMING: THE BIG NERD RANCH GUIDE, 3D , 4TH
EDITION , by Bill Phillips (Author), Chris Stewart (Author), Kristin
Marsicano (Author)
http://riagora.com/pvt_content/android/DynamicLayout.fxp
Steele, J., and To, N. 2010. The Android Developer’s Cookbook. Boston:
Addison-Wesley. ISBN-10: 0321741234 ISBN-13: 9780321741233
http://developer.android.com/guide/components/fragments.html
http
://www.lynda.com/Android-tutorials/Building-Adaptive-Android-Apps-Fragm
ents/164465-2.html?org=sheridanc.ca
29