Vous êtes sur la page 1sur 9

3/3/2015

AndroidFragments

ANDROIDFRAGMENTS
http://www.tutorialspoint.com/android/android_fragments.htm

Copyrighttutorialspoint.com

AFragmentisapieceofanapplication'suserinterfaceorbehaviorthatcanbeplacedinanActivitywhich
enablemoremodularactivitydesign.Itwillnotbewrongifwesay,afragmentisakindofsubacitivity.
Followingareimportantpointsaboutfragment:
Afragmenthasitsownlayoutanditsownbehaviorwithitsownlifecyclecallbacks.
Youcanaddorremovefragmentsinanactivitywhiletheactivityisrunning.
YoucancombinemultiplefragmentsinasingleactivitytobuildamultipaneUI.
Afragmentcanbeusedinmultipleactivities.
Fragmentlifecycleiscloselyrelatedtothelifecycleofitshostactivitywhichmeanswhentheactivity
ispaused,allthefragmentsavailableintheacivitywillalsobestopped.
Afragmentcanimplementabehaviorthathasnouserinterfacecomponent.
FragmentswereaddedtotheAndroidAPIinHoneycombversionofAndroidwhichAPIversion11.
YoucreatefragmentsbyextendingFragmentclassandYoucaninsertafragmentintoyouractivitylayout
bydeclaringthefragmentintheactivity'slayoutfile,asa<fragment>element.
Priortofragmentintroduction,wehadalimitationbecausewecanshowonlyasingleactivityonthescreen
atonegivenpointintime.Sowewerenotabletodividedevicescreenandcontroldifferentparts
separately.Butwiththeintroductionoffragmentwegotmoreflexibilityandremovedthelimitationof
havingasingleactivityonthescreenatatime.Nowwecanhaveasingleacitivitybuteachacitivitycan
compriseofmultiplefragmentswhichwillhavetheirownlayout,eventsandcompletelifecycle.
FollowingisatypicalexampleofhowtwoUImodulesdefinedbyfragmentscanbecombinedintoone
activityforatabletdesign,butseparatedforahandsetdesign.

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/9

3/3/2015

AndroidFragments

TheapplicationcanembedtwofragmentsinActivityA,whenrunningonatabletsizeddevice.However,on
ahandsetsizedscreen,there'snotenoughroomforbothfragments,soActivityAincludesonlythe
fragmentforthelistofarticles,andwhentheuserselectsanarticle,itstartsActivityB,whichincludesthe
secondfragmenttoreadthearticle.

FragmentLifeCycle
Androidfragmentshavetheirownlifecycleverysimilartoanandroidactivity.Thissectionbriefsdifferent
stagesofitslifecycle.

PhaseI:Whenafragmentgetscreated,itgoes
throughthefollowingstates:
onAttach
onCreate
onCreateView
onActivityCreated

PhaseII:Whenthefragmentbecomesvisible,it
goesthroughthesestates:
onStart

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/9

3/3/2015

AndroidFragments

onResume
PhaseIII:Whenthefragmentgoesintothe
backgroundmode,itgoesthroughthesestates:
onPaused
onStop
PhaseIV:Whenthefragmentisdestroyed,it
goesthroughthefollowingstates:
onPaused
onStop
onDestroyView
onDestroy
onDetach

HowtouseFragments?
ThisinvolvesnumberofsimplestepstocreateFragments.
Firstofalldecidehowmanyfragmentsyouwanttouseinanactivity.Forsexamplelet'swewantto
usetwofragmentstohandlelandscapeandportraitmodesofthedevice.
Nextbasedonnumberoffragments,createclasseswhichwillextendtheFragmentclass.The
Fragmentclasshasabovementionedcallbackfunctions.Youcanoverrideanyofthefunctionsbased
onyourrequirements.
Correspondingtoeachfragment,youwillneedtocreatelayoutfilesinXMLfile.Thesefileswillhave
layoutforthedefinedfragments.
Finallymodifyactivityfiletodefinetheactuallogicofreplacingfragmentsbasedonyour

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/9

3/3/2015

AndroidFragments

requirement.
Hereisthelistofimportantmethodswhichyoucantooverrideinyourfragmentclass:
onCreateThesystemcallsthiswhencreatingthefragment.Youshouldinitializeessential
componentsofthefragmentthatyouwanttoretainwhenthefragmentispausedorstopped,then
resumed.
onCreateViewThesystemcallsthiscallbackwhenit'stimeforthefragmenttodrawitsuser
interfaceforthefirsttime.TodrawaUIforyourfragment,youmustreturnaViewcomponent
fromthismethodthatistherootofyourfragment'slayout.Youcanreturnnullifthefragmentdoes
notprovideaUI.
onPauseThesystemcallsthismethodasthefirstindicationthattheuserisleavingthefragment.
Thisisusuallywhereyoushouldcommitanychangesthatshouldbepersistedbeyondthecurrent
usersession.

Example
ThisexamplewillexplainyouhowtocreateyourownFragments.Herewewillcreatetwofragmentsand
oneofthemwillbeusedwhendeviceisinlandscapemodeandanotherfragmentwillbeusedincaseof
portraitmode.Solet'sfollowthefollowingstepstosimilartowhatwefollowedwhilecreatingHelloWorld
Example:

Step

Description

YouwilluseEclipseIDEtocreateanAndroidapplicationandnameitasMyFragmentsundera
packagecom.example.myfragments,withblankActivity.

ModifymainactivityfileMainActivity.javaasshownbelowinthecode.Herewewillcheck
orientationofthedeviceandaccordinglywewillswitchbetweendifferentfragments.

CreateatwojavafilesPM_Fragment.javaandLM_Fragement.javaunderthepackage
com.example.myfragmentstodefineyourfragmentsandassociatedmethods.

Createlayoutsfilesres/layout/lm_fragment.xmlandres/layout/pm_fragment.xmland
defineyourlayoutsforboththefragments.<

Modifythedetaultcontentofres/layout/activity_main.xmlfiletoincludeboththefragments.

Definerequiredconstantsinres/values/strings.xmlfile

RuntheapplicationtolaunchAndroidemulatorandverifytheresultofthechangesdoneinthe
aplication.

Followingisthecontentofthemodifiedmainactivityfile
src/com.example.mycontentprovider/MainActivity.java:
packagecom.example.myfragments;

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/9

3/3/2015

AndroidFragments

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.app.FragmentManager;
importandroid.app.FragmentTransaction;
importandroid.content.res.Configuration;
importandroid.view.WindowManager;
publicclassMainActivityextendsActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
Configurationconfig=getResources().getConfiguration();
FragmentManagerfragmentManager=getFragmentManager();
FragmentTransactionfragmentTransaction=
fragmentManager.beginTransaction();
/**
*Checkthedeviceorientationandactaccordingly
*/
if(config.orientation==Configuration.ORIENTATION_LANDSCAPE){
/**
*Landscapemodeofthedevice
*/
LM_Fragmentls_fragment=newLM_Fragment();
fragmentTransaction.replace(android.R.id.content,ls_fragment);
}else{
/**
*Portraitmodeofthedevice
*/
PM_Fragmentpm_fragment=newPM_Fragment();
fragmentTransaction.replace(android.R.id.content,pm_fragment);
}
fragmentTransaction.commit();
}

CreatetwofragmentfilesLM_Fragement.javaandPM_Fragment.javaunder
com.example.mycontentproviderpackage.
FollowingisthecontentofLM_Fragement.javafile:
packagecom.example.myfragments;
importandroid.app.Fragment;
importandroid.os.Bundle;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
publicclassLM_FragmentextendsFragment{

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/9

3/3/2015

AndroidFragments

@Override
publicViewonCreateView(LayoutInflaterinflater,
ViewGroupcontainer,BundlesavedInstanceState){
/**
*Inflatethelayoutforthisfragment
*/
returninflater.inflate(
R.layout.lm_fragment,container,false);
}
}

FollowingisthecontentofPM_Fragement.javafile:
packagecom.example.myfragments;
importandroid.app.Fragment;
importandroid.os.Bundle;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
publicclassPM_FragmentextendsFragment{
@Override
publicViewonCreateView(LayoutInflaterinflater,
ViewGroupcontainer,BundlesavedInstanceState){
/**
*Inflatethelayoutforthisfragment
*/
returninflater.inflate(
R.layout.pm_fragment,container,false);
}
}

Createtwolayoutfileslm_fragement.xmlandpm_fragment.xmlunderres/layoutdirectory.
Followingisthecontentoflm_fragement.xmlfile:
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px"/>
<!MoreGUIcomponentsgohere>

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/9

3/3/2015

AndroidFragments

</LinearLayout>

Followingisthecontentofpm_fragment.xmlfile:
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#666666">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:textColor="#000000"
android:textSize="20px"/>
<!MoreGUIcomponentsgohere>
</LinearLayout>

Followingwillbethecontentofres/layout/activity_main.xmlfilewhichincludesyourfragments:
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:name="com.example.fragments"
android:id="@+id/lm_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>

<fragment
android:name="com.example.fragments"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>

Makesureyouhavefollowingcontentofres/values/strings.xmlfile:
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">MyFragments</string>

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/9

3/3/2015

AndroidFragments

<stringname="action_settings">Settings</string>
<stringname="hello_world">Helloworld!</string>
<stringname="landscape_message">ThisisLandscapemodefragment
</string>
<stringname="portrait_message">ThisisPortraitmodefragment
</string>
</resources>

Let'strytorunourmodifiedMyFragmentsapplicationwejustcreated.Iassumeyouhadcreatedyour
AVDwhiledoingenvironmentsetup.ToruntheappfromEclipse,openoneofyourproject'sactivityfiles
andclickRun
iconfromthetoolbar.EclipseinstallstheapponyourAVDandstartsitandif
everythingisfinewithyoursetupandapplication,itwilldisplayEmulatorwindowwhereyouwillclickon
Menubuttontoseethefollowingwindow.Bepatiencebecauseitmaytakesometimebasedonyour
computerspeed:

Tochangethemodeoftheemulatorscreen,let'sdothefollowing:
fn+control+F11onMactochangethelandscapetoportraitandviceversa.
ctrl+F11onWindows.
ctrl+F11onLinux.
Onceyouchangedthemode,youwillbeabletoseetheGUIwhichyouhaveimplementedforlandscape
modeasbelow:

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/9

3/3/2015

AndroidFragments

ThiswayyoucanusesameactivitybutdifferentGUIsthroughdifferentfragments.Youcanusedifferent
typeofGUIcomponentsfordifferentGUIsbasedonyourrequirements.

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/9

Vous aimerez peut-être aussi