SlideShare a Scribd company logo
Fragments
Fragments
A Fragment is a portion of the graphical interface of an Activity. It
has its own life cycle and can be added or removed while the
Activity is in the foreground.
A Fragment is added to an Activity within a ViewGroup because
the Fragment defines its graphical interface.
Each Activity has a Back Stack to preserve the states of all the
Fragments replaced in its graphical interface.
Pattern: it is recommended to develop a Fragment which can be
reused in any other Activity regardless of the type of terminal or
configuration.
Fragment
Fragments
The introduction of the Fragment was dictated by the need to
support small smartphone and tablet. The Dual Pane Pattern is
the ideal way to develop an application that supports all of the
Android devices.
Dual Pane Pattern
Fragments
To create a Fragment the class must extend
the Fragment class. The life cycle of a
Fragment is very similar to that of the
Activity.
The lifecycle differs from the Activity one for:
● onAttach(): the Fragment has been inserted
in the GUI of Activity
● onCreateView(): it is used to define the
View, which is the interface of the Fragment
and that ends up in the hierarchy of Activity
● onActivityCreated(): the Activity.onCreate()
is executed
● onDestroyView(): the view is destroyed
● OnDetach(): there is no longer any
connection between the Fragment and
Activity.
Fragment Life Cycle
Fragments
The direct comparison between Fragment
and Activity LifeCycle highlights the
management system of the Fragment added
to the Activity.
You can replace a Fragment with another
because the Fragment Activity has a
BackStack to save the data of all instances
of added Fragment.
Fragment Life Cycle
Fragments
A Fragment can not have a graphical interface. If you want to
assign a layout to a Fragment you must use the method
Fragment.onCreateView().
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
● Inflater: useful to retrieve a view from an xml file in layout
folder
● Container: the ViewGroup that contains the Fragment
● SavedInstanceState: the Bundle used to retrieve data saved
before destroying as for Activity lifecycle
User Interface
Fragments
There are 2 ways to allocate and add a Fragment to an Activity:
● Layout file: when the Activity prepares its GUI and finds a
<fragment /> tag, a Fragment is instantiated using the class
defined in:
android:name="com.example.fragment.ExampleFragment"
● FragmentTransaction: you can add a Fragment to the Activity
at any time when it is in the foreground using the
FragmentManager and FragmentTransaction objects.
A Fragment must have a tag for its identification inside Activity
backstack. In both cases, you can define a tag as a string.
Fragment Activity adding
Fragments
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/list"
android:name="com.example.news.ArticleListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/viewer"
android:name="com.example.news.ArticleReaderFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
Fragment Activity adding –
Layout File
Fragments
In order to add a Fragment to an Activity at runtime you need to
do the following:
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
You must call FragmentTransaction.commit() at the end.
N.B. To support the integration of a Fragment from layouts, the
Fragments have only one constructor and it's a zero-parameters
one.
Fragment Activity adding –
FragmentTransaction
Fragments
To create a new instance of the Fragment and pass parameters
you can use the Static Factory Method:
public class CustomFragment extends Fragment {
private static final String BOOLEAN_KEY = "boolean";
private static final String PARCELABLE_KEY = "parcelable";
public static CustomFragment newInstance (boolean booleanValue,
Parcelable parcelableValue) {
CustomFragment customFragment = new CustomFragment();
Bundle bundle = new Bundle();
bundle.putBoolean(BOOLEAN_KEY, booleanValue);
bundle.putParcelable(PARCELABLE_KEY, parcelableValue);
customFragment.setArguments(bundle);
return customFragment;
}
}
Fragment Activity adding –
Instance creation
Fragments
If it helps, you can declare the zero-paramter constructor as
private so it can not be instantiated without the parameters of
Static Factory Method.
private CustomFragment(){
}
To retrieve the data contained in Bundle at any point in the life
cycle of the Fragment you can invoke the method
Fragment.getArguments () to retrieve the entire Bundle.
getArguments().getBoolean(BOOLEAN_KEY);
getArguments().getParcelable(PARCELABLE_KEY);
Fragment Activity adding –
Instance creation
Fragments
● To retrieve the reference to the Activity that contains the
Fragment you can use the Fragment.getActivity() method:
View listView = getActivity().findViewById(R.id.list);
● To retrieve the reference of the Fragment contained by the
Activity you can use the method:
ExampleFragment fragment = (ExampleFragment)
getFragmentManager().findFragmentById(R.id.example_fragment);
Pattern: never use the casting of Fragment.getActivity () to
retrieve a reference to a particular Activity because this binds him
to the Activity and the Fragment cannot be reused in another
Activity.
Communication with Activity
Fragments
To adapt a Fragment to a variety of Activity, you can declare an
interface within the class of Fragment and let the Activity
implement it:
public class CustomFragment extends Fragment {
public interface OnSomethingHappenedListener{
public void onSomethingHappened();
}
}
public class MainActivity extends ActionBarActivity implements
OnSomethingHappenedListener {
@Override
public void onSomethingHappened() {
}
}
Communication with Activity
Fragments
You need to override the Fragment.onAttach() method (which has
the bound Activity as a parameter) to verify that the Activity is an
instance of the interface.
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnSomethingHappenedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSomethingHappenedListener");
}
}
Communication with Activity
Fragments
In order to notify the Activity that the Fragment needs to add one
or more actions and change, therefore, the ActionBar, the
Fragment must set Fragment.setHasOptionsMenu() as true in
Fragment.onCreate(). The management of the Action Items is
entrusted to methods with the same name as those of Activity:
● Fragment.onCreateOptionsMenu()
● Fragment.onPrepareOptionsMenu()
● Fragment.onOptionsItemSelected()
When the user selects an Action, the first invoked callback is the
Activity one and if this returns false the Fragment one is invoked.
Contextual Action Items

More Related Content

PDF
Android Fragment
PDF
Short Intro to Android Fragments
PPTX
Explanation onAttach() of Fragment class in Android
PPTX
PPT
Introduction to Android Fragments
PDF
Android - Working with Fragments
PDF
Introduction to fragments in android
PDF
[Individual presentation] android fragment
Android Fragment
Short Intro to Android Fragments
Explanation onAttach() of Fragment class in Android
Introduction to Android Fragments
Android - Working with Fragments
Introduction to fragments in android
[Individual presentation] android fragment

What's hot (15)

PDF
Android development session 4 - Fragments
PPTX
Activities, Fragments, and Events
PDF
Fragments anyone
PPTX
深入淺出談Fragment
PDF
Hi AndroidAnnotations
PPTX
Android
ODP
Android App Development - 02 Activity and intent
PDF
Advanced Dagger talk from 360andev
DOCX
STYLISH FLOOR
PDF
Andriod dev toolbox part 2
PDF
Annotation Processing
PDF
Screen Robots: UI Tests in Espresso
PDF
Android ui tips & tricks
PDF
A comprehensive guide on developing responsive and common react filter component
PDF
Android: Intent, Intent Filter, Broadcast Receivers
Android development session 4 - Fragments
Activities, Fragments, and Events
Fragments anyone
深入淺出談Fragment
Hi AndroidAnnotations
Android
Android App Development - 02 Activity and intent
Advanced Dagger talk from 360andev
STYLISH FLOOR
Andriod dev toolbox part 2
Annotation Processing
Screen Robots: UI Tests in Espresso
Android ui tips & tricks
A comprehensive guide on developing responsive and common react filter component
Android: Intent, Intent Filter, Broadcast Receivers
Ad

Viewers also liked (19)

PDF
Android Fragment-Awesome
PPTX
Dori waldman android _course
PDF
Android Fragment Pattern: Communication
PPTX
Android 101 - Introduction to Android Development
PDF
Intro to Google TV
PDF
Mobile in a Nutshell
PPTX
Fragment debugging
PPTX
Spinners, Adapters & Fragment Communication
ODP
Android App Development - 14 location, media and notifications
PPSX
Screen orientations in android
PPTX
Android Training (Storing & Shared Preferences)
KEY
Google I/O 2011, Android Honeycomb Highlights
PDF
Android ui menu
PPT
Fragments notes powerpoint
PDF
Android Location and Maps
PPTX
Dori waldman android _course_2
PPTX
[Android] PLAYING WITH FRAGMENT
PPTX
Fragmentation and types of fragmentation in Distributed Database
PPT
android menus
Android Fragment-Awesome
Dori waldman android _course
Android Fragment Pattern: Communication
Android 101 - Introduction to Android Development
Intro to Google TV
Mobile in a Nutshell
Fragment debugging
Spinners, Adapters & Fragment Communication
Android App Development - 14 location, media and notifications
Screen orientations in android
Android Training (Storing & Shared Preferences)
Google I/O 2011, Android Honeycomb Highlights
Android ui menu
Fragments notes powerpoint
Android Location and Maps
Dori waldman android _course_2
[Android] PLAYING WITH FRAGMENT
Fragmentation and types of fragmentation in Distributed Database
android menus
Ad

Similar to Android App Development - 06 Fragments (20)

PPTX
Tk2323 lecture 6 fragment (new)
PPTX
Android Fragments
PPTX
What the fragments
PPTX
learn about Android Extended and Fragments.pptx
PDF
Multi screenlab
PPTX
fragments-activity.pptx
PDF
Fragments In Android
PPTX
Lesson 4
PPTX
Fragmentation in android
PPTX
Fragment me
 
PPTX
Fragments
DOCX
Activity
DOCX
Activity
DOCX
Activity
DOCX
Activity
PPTX
Android Mobile application development - Event Handling (1).pptx
DOCX
Introduction to Android Fragment and its Lifecycle.docx
PPTX
Android apps development
PPTX
Fragments In Android.pptx
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
Tk2323 lecture 6 fragment (new)
Android Fragments
What the fragments
learn about Android Extended and Fragments.pptx
Multi screenlab
fragments-activity.pptx
Fragments In Android
Lesson 4
Fragmentation in android
Fragment me
 
Fragments
Activity
Activity
Activity
Activity
Android Mobile application development - Event Handling (1).pptx
Introduction to Android Fragment and its Lifecycle.docx
Android apps development
Fragments In Android.pptx
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)

More from Diego Grancini (11)

ODP
Android App Development - 13 Broadcast receivers and app widgets
ODP
Android App Development - 12 animations
ODP
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
ODP
Android App Development - 10 Content providers
ODP
Android App Development - 09 Storage
ODP
Android App Development - 08 Services
ODP
Android App Development - 07 Threading
ODP
Android App Development - 05 Action bar
ODP
Android App Development - 04 Views and layouts
ODP
Android App Development - 03 Resources
ODP
Android App Development - 01 Introduction
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 12 animations
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 10 Content providers
Android App Development - 09 Storage
Android App Development - 08 Services
Android App Development - 07 Threading
Android App Development - 05 Action bar
Android App Development - 04 Views and layouts
Android App Development - 03 Resources
Android App Development - 01 Introduction

Android App Development - 06 Fragments

  • 2. Fragments A Fragment is a portion of the graphical interface of an Activity. It has its own life cycle and can be added or removed while the Activity is in the foreground. A Fragment is added to an Activity within a ViewGroup because the Fragment defines its graphical interface. Each Activity has a Back Stack to preserve the states of all the Fragments replaced in its graphical interface. Pattern: it is recommended to develop a Fragment which can be reused in any other Activity regardless of the type of terminal or configuration. Fragment
  • 3. Fragments The introduction of the Fragment was dictated by the need to support small smartphone and tablet. The Dual Pane Pattern is the ideal way to develop an application that supports all of the Android devices. Dual Pane Pattern
  • 4. Fragments To create a Fragment the class must extend the Fragment class. The life cycle of a Fragment is very similar to that of the Activity. The lifecycle differs from the Activity one for: ● onAttach(): the Fragment has been inserted in the GUI of Activity ● onCreateView(): it is used to define the View, which is the interface of the Fragment and that ends up in the hierarchy of Activity ● onActivityCreated(): the Activity.onCreate() is executed ● onDestroyView(): the view is destroyed ● OnDetach(): there is no longer any connection between the Fragment and Activity. Fragment Life Cycle
  • 5. Fragments The direct comparison between Fragment and Activity LifeCycle highlights the management system of the Fragment added to the Activity. You can replace a Fragment with another because the Fragment Activity has a BackStack to save the data of all instances of added Fragment. Fragment Life Cycle
  • 6. Fragments A Fragment can not have a graphical interface. If you want to assign a layout to a Fragment you must use the method Fragment.onCreateView(). @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } ● Inflater: useful to retrieve a view from an xml file in layout folder ● Container: the ViewGroup that contains the Fragment ● SavedInstanceState: the Bundle used to retrieve data saved before destroying as for Activity lifecycle User Interface
  • 7. Fragments There are 2 ways to allocate and add a Fragment to an Activity: ● Layout file: when the Activity prepares its GUI and finds a <fragment /> tag, a Fragment is instantiated using the class defined in: android:name="com.example.fragment.ExampleFragment" ● FragmentTransaction: you can add a Fragment to the Activity at any time when it is in the foreground using the FragmentManager and FragmentTransaction objects. A Fragment must have a tag for its identification inside Activity backstack. In both cases, you can define a tag as a string. Fragment Activity adding
  • 8. Fragments <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <fragment android:id="@+id/list" android:name="com.example.news.ArticleListFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/viewer" android:name="com.example.news.ArticleReaderFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" /> </LinearLayout> Fragment Activity adding – Layout File
  • 9. Fragments In order to add a Fragment to an Activity at runtime you need to do the following: FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(tag); fragmentTransaction.commit(); You must call FragmentTransaction.commit() at the end. N.B. To support the integration of a Fragment from layouts, the Fragments have only one constructor and it's a zero-parameters one. Fragment Activity adding – FragmentTransaction
  • 10. Fragments To create a new instance of the Fragment and pass parameters you can use the Static Factory Method: public class CustomFragment extends Fragment { private static final String BOOLEAN_KEY = "boolean"; private static final String PARCELABLE_KEY = "parcelable"; public static CustomFragment newInstance (boolean booleanValue, Parcelable parcelableValue) { CustomFragment customFragment = new CustomFragment(); Bundle bundle = new Bundle(); bundle.putBoolean(BOOLEAN_KEY, booleanValue); bundle.putParcelable(PARCELABLE_KEY, parcelableValue); customFragment.setArguments(bundle); return customFragment; } } Fragment Activity adding – Instance creation
  • 11. Fragments If it helps, you can declare the zero-paramter constructor as private so it can not be instantiated without the parameters of Static Factory Method. private CustomFragment(){ } To retrieve the data contained in Bundle at any point in the life cycle of the Fragment you can invoke the method Fragment.getArguments () to retrieve the entire Bundle. getArguments().getBoolean(BOOLEAN_KEY); getArguments().getParcelable(PARCELABLE_KEY); Fragment Activity adding – Instance creation
  • 12. Fragments ● To retrieve the reference to the Activity that contains the Fragment you can use the Fragment.getActivity() method: View listView = getActivity().findViewById(R.id.list); ● To retrieve the reference of the Fragment contained by the Activity you can use the method: ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); Pattern: never use the casting of Fragment.getActivity () to retrieve a reference to a particular Activity because this binds him to the Activity and the Fragment cannot be reused in another Activity. Communication with Activity
  • 13. Fragments To adapt a Fragment to a variety of Activity, you can declare an interface within the class of Fragment and let the Activity implement it: public class CustomFragment extends Fragment { public interface OnSomethingHappenedListener{ public void onSomethingHappened(); } } public class MainActivity extends ActionBarActivity implements OnSomethingHappenedListener { @Override public void onSomethingHappened() { } } Communication with Activity
  • 14. Fragments You need to override the Fragment.onAttach() method (which has the bound Activity as a parameter) to verify that the Activity is an instance of the interface. @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnSomethingHappenedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnSomethingHappenedListener"); } } Communication with Activity
  • 15. Fragments In order to notify the Activity that the Fragment needs to add one or more actions and change, therefore, the ActionBar, the Fragment must set Fragment.setHasOptionsMenu() as true in Fragment.onCreate(). The management of the Action Items is entrusted to methods with the same name as those of Activity: ● Fragment.onCreateOptionsMenu() ● Fragment.onPrepareOptionsMenu() ● Fragment.onOptionsItemSelected() When the user selects an Action, the first invoked callback is the Activity one and if this returns false the Fragment one is invoked. Contextual Action Items