Fragments in Android

Fragments enable you to divide your Activities into fully encapsulated reusable components, each with its own lifecycle and UI.

The primary advantage of Fragments is the ease with which you can create dynamic and flexible UI designs that can be adapted to suite a range of screen sizes — from small-screen smartphones to tablets.

Each Fragment is an independent module that is tightly bound to the Activity into which it is placed. Fragments can be reused within multiple activities, as well as laid out in a variety of combinations to suit multipane tablet UIs and added to, removed from, and exchanged within a running Activity to help build dynamic UIs

Fragments provide a way to present a consistent UI optimized for a wide variety of Android device types, screen sizes, and device densities.

Creating New Fragments

Extend the Fragment class to create a new Fragment, (optionally) defining the UI and implementing the functionality it encapsulates.

In most circumstances you’ll want to assign a UI to your Fragment. It is possible to create a Fragment that doesn’t include a UI but instead provides background behavior for an Activity

Fragment skeleton code

package com.paad.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MySkeletonFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, 
 ViewGroup container,
 Bundle savedInstanceState) {
 // Create, or inflate the Fragment’s UI, and return it. 
 // If this Fragment has no UI then return null.
 return inflater.inflate(R.layout.my_fragment, container, false);
 }
}

The Fragment Lifecycle

The lifecycle events of a Fragment mirror those of its parent Activity; however, after the containing Activity is in its active — resumed — state adding or removing a Fragment will affect its lifecycle independently.

Fragments include a series of event handlers that mirror those in the Activity class. They are triggered as the Fragment is created, started, resumed, paused, stopped, and destroyed. Fragments also include a number of additional callbacks that signal binding and unbinding the Fragment from its parent Activity, creation (and destruction) of the Fragment’s View hierarchy, and the completion of the creation of the parent Activity

The Fragment Lifecycle

Fragment lifecycle event handlers

package tech.codingpoint.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MySkeletonFragment extends Fragment {
 // Called when the Fragment is attached to its parent Activity.
 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 // Get a reference to the parent Activity.
 }
 // Called to do the initial creation of the Fragment.
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 // Initialize the Fragment.
 }
 // Called once the Fragment has been created in order for it to
 // create its user interface.
 @Override
 public View onCreateView(LayoutInflater inflater, 
 ViewGroup container,
 Bundle savedInstanceState) {
 // Create, or inflate the Fragment’s UI, and return it. 
 // If this Fragment has no UI then return null.
 return inflater.inflate(R.layout.my_fragment, container, false);
 }
 // Called once the parent Activity and the Fragment’s UI have 
 // been created.
 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);
 // Complete the Fragment initialization – particularly anything
 // that requires the parent Activity to be initialized or the 
 // Fragment’s view to be fully inflated.
 }
 // Called at the start of the visible lifetime.
 @Override
 public void onStart(){
 super.onStart();
 // Apply any required UI change now that the Fragment is visible.
 }
 // Called at the start of the active lifetime.
 @Override
 public void onResume(){
 super.onResume();
 // Resume any paused UI updates, threads, or processes required
// by the Fragment but suspended when it became inactive.
 }
 // Called at the end of the active lifetime.
 @Override
 public void onPause(){
 // Suspend UI updates, threads, or CPU intensive processes
 // that don’t need to be updated when the Activity isn’t
 // the active foreground activity.
 // Persist all edits or state changes
 // as after this call the process is likely to be killed.
 super.onPause();
 }
 // Called to save UI state changes at the
 // end of the active lifecycle.
 @Override
 public void onSaveInstanceState(Bundle savedInstanceState) {
 // Save UI state changes to the savedInstanceState.
 // This bundle will be passed to onCreate, onCreateView, and
 // onCreateView if the parent Activity is killed and restarted.
 super.onSaveInstanceState(savedInstanceState);
 }
 // Called at the end of the visible lifetime.
 @Override
 public void onStop(){
 // Suspend remaining UI updates, threads, or processing
 // that aren’t required when the Fragment isn’t visible.
 super.onStop();
 }
 // Called when the Fragment’s View has been detached.
 @Override
 public void onDestroyView() {
 // Clean up resources related to the View.
 super.onDestroyView();
 }
 // Called at the end of the full lifetime.
 @Override
 public void onDestroy(){
 // Clean up any resources including ending threads,
 // closing database connections etc.
 super.onDestroy();
 }
 // Called when the Fragment has been detached from its parent Activity.
 @Override
 public void onDetach() {
 super.onDetach();
 }
}

Fragment-Specific Lifecycle Events

Attaching and Detaching Fragments from the Parent Activity

The full lifetime of your Fragment begins when it’s bound to its parent Activity and ends when it’s been detached. These events are represented by the calls to onAttach and onDetach, respectively

As with any handler called after a Fragment/Activity has become paused, it’s possible that onDetach will not be called if the parent Activity’s process is terminated without completing its full lifecycle.

The onAttach event is triggered before the Fragment’s UI has been created, before the Fragment itself or its parent Activity have finished their initialization. Typically, the onAttach event is used to gain a reference to the parent Activity in preparation for further initialization tasks.

Creating and Destroying Fragments

The created lifetime of your Fragment occurs between the first call to onCreate and the final call to onDestroy. As it’s not uncommon for an Activity’s process to be terminated without the corresponding onDestroy method being called, so a Fragment can’t rely on its onDestroy handler being triggered.

Creating and Destroying User Interfaces

A Fragment’s UI is initialized (and destroyed) within a new set of event handlers: onCreateView and onDestroyView, respectively.

Use the onCreateView method to initialize your Fragment: Inflate the UI, get references (and bind data to) the Views it contains, and then create any required Services and Timers

Once you have inflated your View hierarchy, it should be returned from this handler:

return inflater.inflate(R.layout.my_fragment, container, false);

Leave a Comment