android activity - cs 4720 · android activity cs 4720 – mobile application development source:...
TRANSCRIPT
CS4720
AndroidActivity
CS4720– MobileApplicationDevelopment
Source:developer.android.com
CS4720
Activity• Conceptually,anActivityisasinglescreenofyourapplication
• Inotherwords,anAppreallyisacollectionofrelatedActivities
• ConsidereachActivitybothascreenandafeature
• AppscanactivateActivitiesinotherApps
2
CS4720
TheAppLifecycle
3
CS4720
TheActivity
4
CS4720
TheLifecycle• AnActivitycanbe:
– Resumed– activeandintheforegroundwithuserfocus
– Paused– active,butis“coveredup”byanotheractivitythatcurrentlyhastheuserfocus
– Stopped– currentlyresidinginthebackgroundandisnotattachedtothewindowmanagerandisnotvisible;canbekilledbysystemifmemoryisneeded
5
CS4720
LifecycleCallbacks
6
CS4720
LifecycleCallbacks• Makesuretomakethecorrectcallsinthecorrectmethods!
• IfyoudoeverythinginonCreate(),thenproblemscouldoccurwhenyouswitch
• Onadevicerotation,onDestroy()/onCreate()iscalled
• ConsidersavingstateusingonSaveInstanceState()toretainAppstatebetweenswitching
7
CS4720
onCreate()• CalledwhenAppisstartingfresh• ThisiswheresetContentView()(settingtheUI)iscalled
• ThisiswhyonCreate()iscalledonarotation–youmaybeusingadifferentlayout
8
CS4720
NextSteps• onStart()- CalledrightbeforeActivityisshowntouser
• onResume()– CalledjustbeforeActivitywillstartacceptinguserinput
• onPause()– CalledwhenanotherActivitywillcallonResume()– usedtosaveremainingchanges
• onStop()– CalledwhenActivityisnolongervisible
9
CS4720
UI• UIcomponentscomefromtheViewclass• AViewcontrolsasetofrectangularspaceandcanrespondtouserinteraction
• Canbethewholescreen,orjustasmallportion
• Technically,a“widget”(likeabutton)isaverysmallView
• ALayout(andit’sxml)isagroupofViewswithlocationinstructions
10
CS4720
AddingtotheManifest• AllActivitiesmustbedefinedintheandroidmanifest.xml file
• IntentsthatthisActivitycanrespondtoarealsodefinedhere
11
CS4720
LaunchinganewActivity• TolaunchanewActivity,createanIntentforthatActivityandsenditout
12
CS4720
Fragments• ConsideraFragmentasortof“sub-Activity”• AnActivitycanbemadeupofnumerousFragments,eachwiththeirownfeatures
• Thisisusefulwhenyouwanttomove/reordercomponentsfordifferentdisplaysizes/rotations
• AFragmentobeystheActivity’slifecyclestate
13
CS4720
Fragments
14
CS4720
Fragments• AFragmenthas:
– Itsownlifecyclecalls– Itsownlayouts– Itsownviews
• Infact,aFragmentlooksalmostexactlylikeanActivity!
• ToaddaFragment,instantiateitinthelayoutoftheActivity
15
CS4720
FragmentManager• ThemainbenefitsFragmentsarereusabilityandaddressability
• FragmentscanbeaccessedthroughtheFragmentManager andcanbeswappedontheflywhiletheAppisrunning
• FragmentscanaddresstheActivitythatcontainsthem,allowingforsharingofdatabetweenFragments
16