0% found this document useful (0 votes)
796 views9 pages

Android Fragments PDF

A Fragment is a piece of an application's user interface or behavior that can be placed in an activity which enable more modular activity design. A Fragment has its own layout and its own behavior with its own lifecycle callbacks. You can combine multiple fragments in a single activity to build a multipane UI.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
796 views9 pages

Android Fragments PDF

A Fragment is a piece of an application's user interface or behavior that can be placed in an activity which enable more modular activity design. A Fragment has its own layout and its own behavior with its own lifecycle callbacks. You can combine multiple fragments in a single activity to build a multipane UI.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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

You might also like