Android Core

Android Fragment Lifecycle – multiple screen support

Fragment lifecycle is an important aspect to take into account before using fragments. Every developer, that wants to develop an application in Android, has to face the mobile phone fragmentation problem or the multiple screen size support.

In other words there are many smartphone on the market with different screen resolution and different screen density. To make the situation more complex, if possible, there are not only smartphone but tablets also. It is clear to everyone that there are big differences between these two device classes in terms of screen size. Well, when we develop an application we have to keep in mind that it can works on different devices and it has to be optimised so that the user experience is fully satisfied. This creates many problems because we have to adjust the application so that it behaves differently when it runs on a smartphone or a tablet. What said until now is known as multiple screen support. In a previous post (How to support multiple screen in Android), i talked about how to support multiple screen using Android features like creating different layouts and so on. This is a technique that can be still used but it isn’t enough.

A classic example it is an application that have an item list and when user clicks an item in this list the app shows the item details. Well in this case we could have different behaviours if the app runs on a smartphone or tablet. On a smartphone we must have two activities to accomplish this task.

Android_fragment_details



and when user clicks on an item
Android_fragment_list



while in the tablet case we want to “use” all the device screen to show the details near the item list.


Android_fragment-tablet

As it is clear from the example above we would like to have a way to combine “activities” so that they can be used at the same time or in a sequence where one calls the other. We want to organize the screen layout without rewriting the code. This can’t be done only using multiple layouts we need something else.

Fragment

Since Android 3.0 was introduced a new “concept” called Fragment. A fragment is a piece of android code with its layout that can be arranged and combined together to have different layouts.  Using fragments we can re-use the code and satisfy at the same time the device screen size requirements. A fragment can’t live by itself but only inside an Activity and this one can hold several fragments.  It is important to note that fragments can be combined with other activity elements so that you don’t have to rewrite all the activity interface. So using fragment we can manipulate the master-detail app (shown above) in this way:

on a smartphone

and when it runs on a tablet we have:

FRAGMENT LIFECYCLE

Now we know when it is useful to use fragments, we need to know how they work. A fragment lives only inside an Activity that acts as a container.Each fragment has its own view hierarchy that can be inflated as we do usually.  A fragment lifecycle is more complex than the activity lifecycle because it has more states. These lifecycle states are shown below:

Let’s move from the top to the bottom. At very beginning of the fragment life the method onInflate is called. We have to notice that this method is called only if we define fragment directly in our layout using the tag <fragment>. In this method we can save some configuration parameter and some attributes define in the XML layout file. After this step onAttach is called. This method is called as soon as the fragment is “attached” to the “father” activity and we can this method to store the reference about the activity. After it we have onCreate. It is one of the most important step, our fragment is in the creation process. This method can be used to start some thread to retrieve data information, maybe from a remote server. The onCreateView is the method called when the fragment has to create its view hierarchy. During this method we will inflate our layout inside the fragment as we do for example in the ListView widget. During this phase we can’t be sure that our activity is still created so we can’t count on it for some operation. We get notified when the “father” activity is created and ready in the onActivityCreated. From now on, our activity is active and created and we can use it when we need. The next step is onStart method. Here we do the common things as in the activity onStart, during this phase our fragment is visible but it isn’t still interacting with the user.When the fragment is ready to interact with user onResume is called. At the end of this phase our fragment is up and running!!

Then it can happen that the activity is paused and so the activity’s onPause is called. Well onPause fragment method is called too. After it it can happen that the OS decides to destroy our fragment view and so onDestroyView is called. After it, if the system decides to dismiss our fragment it calls onDestroy method. Here we should release all the connection active and so on because our fragment is close to die. Even if it is during the destroy phase it is still attached to the father activity. The last step is detach the fragment from the activity and it happens when onDetach is called.

How to create a Fragment

Once we know the fragment lifecycle, we still need to know how to create it and attach it to an activity. The first thing we need to know is that if we want to create our fragment we have to extend android.app.Fragment. So let’s suppose we have a fragment called Fragment1, to create and define it we have:

public class Fragment1 extends Fragment {
...
}

As we said before, a fragment exists only inside an Activity so need to define it somehow somewhere. We have two choices:

  • Define it directly inside XML layout file
  • Define a place holder in XML layout file and manage the fragment dynamically directly inside our Activity

The way we define our fragment impacts on its lifecycle because in the first case onInflate is called while in the second case the lifecycle start from onAttach method.

If we define the fragment in the XML we have simply

<fragment android:id="@+id/f1" 
              class="com.survivingwithandroid.fragment.Fragment1"
              android:layout_width="match_parent"
              android:layout_height="20dp"/>

While if we define our fragment using a place holder we need to do some other work.

Layout Frameset and Fragment

If we define our fragment inside XML layout file we don’t have much freedom to modify dynamically the fragment. There’s another way we can use to achieve more freedom: we can use <FrameLayout>. In the XML layout file we have:

<FrameLayout android:id="@+id/fl1" 
             android:layout_width="match_parent"
             android:layout_height="200dp"/>

We need a bit more wok on activity side, because we have to instantiate by ourselves the fragment and “insert” it in this FrameLayout.

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Fragment2 f2 = new Fragment2();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fl1, f2);
    ft.commit();
}

We will talk more about FragmentTransaction and so on in the next posts.
 

Francesco Azzola

He's a senior software engineer with more than 15 yrs old experience in JEE architecture. He's SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. He is an android enthusiast and he has worked for long time in the mobile development field.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anas Azeem
Anas Azeem
10 years ago

You have left the tutorial in between, I was really starting to like the approach you used to explain the Fragments and its usage for multiple screen support. But, where is the later part???.

There is no link to it, its been more than a month to the first part.

Anas Azeem
Anas Azeem
10 years ago

Thank You, its awesome and exactly what I wanted.

anony
anony
10 years ago

I think there is a problem with your related links widget, it shows the currently visited link also, please correct it.

Back to top button