Android tutorial : Using Fragments to divide the screen into multiple Activity

Android API version 3.0, known as Honeycomb, introduced a new concept called "Fragment".
A Fragment is an independent component which can be connected to an activity. 
A Fragment typically defines a part of a user interface but it is possible to define  headless Fragments, i.e. without user interface.It represents a behavior or a portion of user interface in an Activity.

Fragment Lifecycle  
A fragment is always connected to an activity. 


 onAttach() 
 is called when the Fragment instance is associated with an Activity instance. This does not mean the Activity is fully initialized.

onCreate()
The system calls this when creating the fragment.

onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. 
Here you can inflate a layout via the inflate() method call of  the Inflator object passed as a parameter to this method. There is no need to implement this method for headlessfragments.

onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). 

 onActivityCreated() 
is called after the onCreateView() method when the host activity is created. Here you can instantiate objects which require a Context object.
Fragments don't subclass the Context, you have to use the getActivity() method to get 
the parent activity.


 onStart()
 is called once the fragment gets visible.

onResume()
 is called when the Fragment becomes visible, and is running.

onStop()
 method is called when the Fragment is about to stop running.

We will see now an example to show you what is the practical significance of this tutorial.
we will realize  step by step a little app. This application will display a list of URLs. Clicking on an item in the list will display the web site. In phone (Portrait Mode) we will have the list of URLs all over the screen, and clicking on an item will start a new activity that will display the web site. However,in tablet (or in Landscape mode )we will have the list of URLs and web site contents on the same screen. 
For Smartphones we will have  View1 then view2. However for  Tablet (and for landscape mode) we will have  View1 AND view2.
 Each view is a fragment that has an XML file and a Java class. 

Some Activities display one or two fragments depending on the size of the screen. So they will have two XML files.

Commentaires

Posts les plus consultés de ce blog

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json

Connexion d'une application Android et une base de données externe Mysql avec web services php Json (opérations CRUD)