Android TutorialsNo Comments

1141 views.

Up until now we have used activities as drivers to display views to the screen. The previous example each screen is associated with an activity that is used to render and manage the user interaction with the view. All that changes in this lecture. We move away from activities and start to use fragments — a fragment is now used to render and manager a particular UI view. Think of fragments as lightweight activities for now. Your application still needs activities but we don’t use them to solely render views. Most applications, and ones we will develop, include one or more activity and fragments.

What are fragments?

  • Fragments are parts of application’s UI or behavior that are integrated into activities — a fragment needs an activity to run.
  • Fragments are flexible and reusable components defined by the programmer
  • each fragment has its own lifecycle and associated UI (for example, a fragment for the user to enter profile information, another one to render maps).
  • Fragments present a consistent UI across different apps and devices; fragments are flexible in adapting the user experience across these different environments.

In implementation there are considerable differences; for example, an activity has to be specified in the manifest, while fragments do not because they can only exist in the context of an activity and are coupled to the activity state. While fragments are strongly integrated into the UI you can use fragments without a view or UI components. Fragments can implement a number of application behaviors, such as, code to handle listeners, files, database, etc. These types of fragments can be thought of as invisible worker for the activity — more later on this. For now we will just consider fragments when applied to the UI.

Why use fragments over activities?

A fragment is a modular part of an activity. It has its own lifecycle and receives its own input events. Fragments can created, added or removed while the activity is running. Consider a fragment a “sub activity” that you can reuse in different activities. But you could ignore fragments and just use activities if you wish — but not recommend. Why use fragments over activities? Well fragments are wired to create reusable Android user inferences components — however, it is true to say you can implement similar application UIs with a pure activity solution, which might be confusing for students. Here are some reasons why you should use fragments as a designer:

  • Consider the diagram below. You are designing a cool new app that you want gazillions of people to use on all sorts of phones and tablets with different sized screens. The figure shows how your UI based on fragment design could run on a tablet and phone UI; in the case of the tablet with larger screen real estate the UI fragment components are rendered side by side but on the phone with a smaller form factor the two fragments are treated differently and brought into focus at different times. The activity that handles the UI is smart enough to adapt the UI to the type of device.

fragments

  • As we will see in the sample project code ActionTab fragments have been integrated into UI components such as ActionBar which is a the recommend way to build a common UI feel across different apps. We will discuss ActionBar later in these notes where we bind tabs (to navigate your app) on the ActionBar to fragments. When we look at the callback (i.e., ActionBar.TabListener interface) for handling the event when the user taps a tab the interface passes a FragmentTransaction as an input argument to the onTabSelected method. In brief, many UI components assume you are using fragments and not activities — as a result, fragments are wired into the UI and activities are not.

Fragment and activities akin to processes and threads

Fragments are reusable UI but can also be considered lightweight in how they handle operations on the UI. As I mentioned before you can do most things with activities that fragments do but consider for the moment (if you did this) the relationship between design using all processes or threaded design. Fragments can be considered to be threads in such a choice, as shown below.

sthreads

Fragment Lifecycle

Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

A fragment runs with in the activity and the activity lifecycle that we discussed. So it an activity is stopped so are all its fragments. Similarly if the activity is destroyed so are all the associated fragments. However, when an activity is running (i.e., onResume() state) fragments can be independently managed — added, replaced or removed. As we will see what we discuss the ActionTab application we will use fragment transactions to remove and replace fragments associated with the action bar tabs: such as:

  • ft.remove(fragment); remove a fragment from the UI
  • ft.replace(R.id.fragment_container, fragment); replace one fragment (or view) with another.

These fragment transactions allow the activity to manage the back stack – a back stack entry in the activity is a record of the fragment transaction that occurred. This, for example, allows the user to reverse a fragment transaction (navigate backwards), by pressing the back button.

The fragment lifecycle diagram shown below looks complicated but as we discuss it consider that this set of fragment states run inside of the running state of the activity lifecycle diagram we discussed in earlier lecture on activity lifecycle. Therefore the state diagram shown below is only valid when the activity associated with the fragment

fragment-lifecycle

Like the activity lifecycle the fragment lifecycle is represented by a bunch of states and associated event handlers, which are triggered when a fragment is:

  • created
  • resumed
  • paused
  • stopped
  • destroyed

In addition there are a number of callbacks associated with a number of fragment specific events, such as, 1) binding and unbinding a fragment from its activity; 2) when a fragment is created and destroyed. If you look at the core states shown in the figure you see:

  • fragment is added
  • fragment is active
  • fragment is destroyed

Fragment lifecycle events

Many events can occur between these states — for example the user can hit the back button.

  • onAttach() is called when the Fragment is attached to its parent activity
  • onCreate() is called to initially create the fragment
  • onCreateView() is called to created its user interface — it inflates the fragment UI
  • onActivityCreated() is called once the parent activity and the fragment UI are created.
  • onStart() is called the start of the visible lifetime, any UI changes can be applied before the fragment goes visible
  • onResume() is called at the start of the active lifetime such as resuming any paused UI updates needed by the fragment that were suspended when it became inactive.
  • onPause() called at the end of the active lifetime; persist all edits or state changes, suspend UI updates, threads, or CPU intensive processes that don’t need to be updated when the Activity isn’t the active foreground activity
  • onSaveInstanceState() called to save UI state changes at the end of the active lifecycle
  • void onStop() called at the end of the visible lifetime
  • onDestroyView() called when the fragment’s view is detached
  • onDestroy() called at the end of the full lifetime
  • onDetach() called when the Fragment has been detached from its parent activity.

If we consider the ActionTab app it has four fragments – one for each tab view. As the use taps through the tab options the fragment transitions through the states in the lifecycle diagram — moving say from being in focus in onResume() to hidden in onPause(). But the complete fragment lifecycle is tightly coupled to the activity but also governed by the user interaction with the UI (as is the case with the ActionTab app). The activity can dynamically construct the UI and its associated fragments — such as adding and removing fragments where each fragment transitions through its full, visible and active lifecycle several times within the lifetime of its parent activity — for example as a fragment is added and removed from the view.

onAttach() and onDetach() events

The lifecycle starts and ends when a fragment is attached and detached from its parent activity. The onAttach() event occurs before the fragment’s UI is created and before the fragment or its parent activity have completed initialization. Keep this in mind when we are looking at the ActionTab activity’s onCreate() when it creates its fragments. It is a good idea to create fragments in the activities onCreate() to ensure they are created only once in the fragment lifetime.

onCreateView() event

The fragment’s UI is created and destroyed in onCreateView() and onDestroyView() callbacks, respectively. The onCreateView() method initializes the fragment by inflating the UI, getting references and binding any data to the views that it contains — and then any addition initialization such as setting up services (we will talk about services later on in the course).

onCreateView(): ActionTab example

The onCreateView()’s main job in code we will write is a one liner — taken from FindFragment.java in the ActionTab app:

return inflater.inflate(R.layout.findfragment, container, false)

An example of a fragment layout

The R.layout.findfragment is the ID for an XML layout resource to load (e.g., R.layout.findfragment). This is defined in the res/layout/findfragment.xml of the ActionTab project. This specifies the UI for the fragment, which is just a simple image but could be a sophisticated view group.

Creating fragments and inflating: MeetFragment.java example

A fragment extends the Fragment class as shown below. When the MainActivity creates the fragments it calls onCreateView() for all fragments. All onCreateView() creates and returns the view hierarchy associated with the fragment– essentially it returns the view for the fragment’s UI. The code below overrides the onCreateView() handler into inflate and return the requires view hierarchy; that is, R.layout.meetfragment, as shown below. Note, if your fragment does not use a UI (such as providing the activity with background behavior) you do not inflate of course.

Importantly, fragments do not have to be registered in the manifest like activities are. And, as the fragment lifecycle, fragments are tied to the state of the activity so this makes good sense; that is, they can’t exist without an activity.

 

Be the first to post a comment.

Add a comment