1.2 Fragment Lifecycle and Communications

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

Advanced Android Development

Fragments

Lesson 1

This
Thiswork
workisislicensed
licensedunder
underaa
Advanced Android Development Fragments Creative
CreativeCommons
CommonsAttribution
Attribution4.0
4.0Inter
Inter 1
national
nationalLicense
License
1.2 Fragment lifecycle and
communications
Using the Fragment lifecycle and
communicating with an Activity

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 2
national License
Contents

● Understanding the Fragment lifecycle


● Using Fragment lifecycle callbacks
● Using Fragment methods and Activity context
● Communicating between Fragment and Activity

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 3
national License
Understanding
the Fragment
lifecycle

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 4
national License
The Fragment lifecycle

● Fragment lifecycle is similar to Activity lifecycle


● Lifecycle callbacks define how Fragment behaves in each
state

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 5
national License
Fragment lifecycle states

● Activity (host)
Activity

adds Fragment Fragment added

● States that a onCreate()


onCreateView()

Fragment can be in: Active Stopped

onDestroyView()

○ Active (or resumed) onPause()

○ Paused Paused

○ Stopped

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 6
national License
How Activity affects Fragment lifecycle
Activity state Fragment callbacks triggered Fragment lifecycle
Created ● onAttach() Fragment is added and its
● onCreate() layout is inflated
● onCreateView()
● onActivityCreated()
Started ● onStart() Fragment is active and visible
Resumed ● onResume() Fragment is active and ready
for user interaction

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 7
national License
How Activity affects Fragment lifecycle

Activity state Fragment callbacks triggered Fragment lifecycle


Paused ● onPause() Fragment is paused because
Activity is paused
Stopped ● onStop() Fragment is stopped and no
longer visible
Destroyed ● onDestroyView() Fragment is destroyed
● onDestroy()
● onDetach()

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 8
national License
Using Fragment
lifecycle
callbacks

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 9
national License
Callbacks to make Fragment active

● onCreate(): Initialize Fragment components and variables


● onCreateView(): Inflate the Fragment XML layout

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 10
national License
Initialize the Fragment in onCreate()
Override onCreate(Bundle savedInstanceState):
● System calls onCreate() when the Fragment is created
● Initialize Fragment components and variables (preserved
if the Fragment is paused and resumed)
● Always include super.onCreate(savedInstanceState)
in lifecycle callbacks

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 11
national License
Display layout in onCreateView()
Override
onCreateView(LayoutInflater inflater, ViewGroup c
ontainer, Bundle savedInstanceState)
:
● Inflate XML layout—required if Fragment has a UI
● System calls this method to make Fragment visible
● Must return the root View of Fragment layout
or null if the Fragment does
Advanced Android Development
not have a UI
This work is licensed under a
Fragments
Creative Commons Attribution 4.0 Inter 12
national License
More Fragment lifecycle callbacks
● onAttach(): Called when Fragment is first attached to Activity
● onPause(): Called when Activity is paused
● onResume(): Called by Activity to resume a visible Fragment
● onActivityCreated(): Called when Activity onCreate() method
has returned
● onDestroyView(): Called when View previously created by
onCreateView() is detached from Fragment

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 13
national License
Callback for final initialization
onActivityCreated(): Called when the Activity
onCreate() method has returned
● Called after onCreateView() and before
onViewStateRestored()
● Retrieve views or restore state
● Use setRetainInstance() to keep Fragment instance
when Activity is recreated
This work is licensed under a
Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 14
national License
Use onDestroyView

Use onDestroyView() to perform action after Fragment is


no longer visible
● Called after onStop() and before onDestroy()
● View that was created in onCreateView() is destroyed
● A new View is created next time Fragment needs to be
displayed

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 15
national License
Using Fragment
methods and
Activity context

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 16
national License
Use the Activity context

When Fragment is active or resumed:


● Use getActivity() to get the Activity that started the
fragment
● Find a View in the Activity layout:
View listView = getActivity().findViewById(R.id.list);

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 17
national License
Call methods in the Fragment

Get Fragment by calling findFragmentById() on


FragmentManager:
ExampleFragment fragment = (ExampleFragment)
getFragmentManager().findFragmentById(R.id.example_fragment);
// ...
mData = fragment.getSomeData();

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 18
national License
Use the back stack (1)

● Add Fragment to back stack: addToBackStack(null)

fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 19
national License
Use the back stack (2)

● Host Activity maintains back stack even after Fragment


is removed
● User can navigate back to Fragment with Back button

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 20
national License
Fragment
communications

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 21
national License
Activity and Fragment communications
● Activity can send data to
Fragment and receive data
from Fragment
● All Fragment-to-Fragment
communication is done
through host Activity

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 22
national License
Send data to Fragment
In Fragment newInstance() factory method:
● Create Bundle
● Use setArguments(Bundle) to supply Fragment
construction arguments

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 23
national License
Fragment factory method
newInstance() factory method:
public static SimpleFragment newInstance(int choice) {
SimpleFragment fragment = new SimpleFragment();
Bundle arguments = new Bundle();
arguments.putInt(CHOICE, choice);
fragment.setArguments(arguments);
return fragment;
}

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 24
national License
Use the Fragment factory method

Include data (such as mRadioButtonChoice) in call to


Fragment from Activity:
SimpleFragment fragment =
SimpleFragment.newInstance(mRadioButtonChoice);

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 25
national License
Use data from Activity in Fragment
● Before drawing Fragment View, get arguments from
Bundle using getArguments()
● Use onCreate() or onCreateView()
if (getArguments().containsKey(CHOICE)) {
mRadioButtonChoice = getArguments().getInt(CHOICE);
// ...
}

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 26
national License
Retrieve data from Fragment
● In Fragment:
○ Define interface (such as a listener) with callback method(s)
○ Override onAttach() to retrieve interface implementation
(check if the Activity implements the interface)
○ Call interface method to pass data as parameter

● In Activity:
○ All Activity classes using Fragment must implement interface
○ Use the interface callback method(s) to retrieve data

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 27
national License
Define interface and callback methods
In Fragment: Define interface (such as a listener) with
callback method (such as onRadioButtonChoice())

interface OnFragmentInteractionListener {
void onRadioButtonChoice(int choice);
}

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 28
national License
Retrieve interface implementation
Retrieve interface implementation from Activity:
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener)
context;
} else {
// ...
This work is licensed under a
Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 29
national License
Call interface method to pass data
public void onCheckedChanged(RadioGroup group, int checkedId) {
// ...
switch (index) {
case YES: // User chose "Yes."
mListener.onRadioButtonChoice(YES);
break;
case NO: // User chose "No."
mListener.onRadioButtonChoice(NO);
break;
// ...
}
This work is licensed under a
Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 30
national License
Implement interface in Activity
Activity must implement the interface defined in the
Fragment:

public class MainActivity extends AppCompatActivity


implements SimpleFragment.OnFragmentInteractionListener {

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 31
national License
Use the callback in the Activity
Activity can then use onRadioButtonChoice() callback:

@Override
public void onRadioButtonChoice(int choice) {
mRadioButtonChoice = choice;
// Use mRadioButtonChoice in Activity
// ...
}

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 32
national License
What's next?

● Concept chapter:
1.2 Fragment lifecycle and communications
● Practical: 1.2 Communicating with a Fragment

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 33
national License
END

This work is licensed under a


Advanced Android Development Fragments Creative Commons Attribution 4.0 Inter 34
national License

You might also like