Académique Documents
Professionnel Documents
Culture Documents
com
alvinalexander
ScalaCookbook
ByAlvinAlexander
Ebook:$27.99
Print&Ebook:$60.49
Print:$54.99
Buyfromoreilly.com
AnAndroidcheatsheet(mynotes,main
categories concepts)
ByAlvinAlexander.Lastupdated:July232016
alaska(25)
android(138)
Thispageisalittleunusual
bestpractices(63)
career(50) formeitsbasicallyaterse TableofContents
colorado(21) summaryofwhatIknow
cvs(27)
aboutAndroid.Icreatedit GettingstartedwithAndroid
design(33)
drupal(120)
becauseItendto(a)work MainAndroidconcepts
eclipse(6) withAndroidforafew
funny(3) weeksormonths,andthen Androidfilesandfolders
gadgets(108)
(b)getawayfromitfor Activity
git(15)
intellij(4) severalmonths,sothis
java(429) pagehelpsmereload Fragmentclass
jdbc(26) everythingintomybrain. Layouts(Containers)
swing(74)
jsp(9)
UIComponents/Widgets
latex(26)
linux/unix(289)
http://alvinalexander.com/android/androidcheatsheetmainconcepts 1/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
linux/unix(289)
Idon'toffermuch ActionBar
macosx(315)
mysql(54) discussionherethisis
Intents
ooa/ood(11) mostlyjustaquickAndroid
perl(156) referencepage.Ihave Androidcommandline
php(97)
postgresql(17)
writtenalotmoreabout Codesnippets
programming(43) Android,andyoucan
ruby(56) followthislinktomy
scala(640)
Androidtutorials,oryou
sencha(23)
servlets(10)
cansearchmywebsitefor
technology(84) Android. TableofContents
testing(13)
uml(24)
zen(47)
Gettingstartedwith
Android
ThebestwaytowriteAndroidcodetoday(2016)istouseAndroidStudio
asyourIDE
AndroidStudioisfree,andit'screated/maintainedbyGoogle
ThebestbookIvefoundisAndroidProgramming:TheBigNerdRanch
Guide.
TheBusyCoder'sGuidetoAndroidDevelopmentisalsouseful,butIthink
itshouldbemorelike$25
IfyouwanttocreateAndroidgames,TheBeginnersGuidetoAndroid
GameDevelopmentisanexcellentstarterbook
31DaysofAndroidbyChrisRisnerlookshelpful
MainAndroidconcepts
ThemainAndroidconceptsyouneedtograspare:
AndroidManifest.xmlyourappstartswiththemainmethodyou
declareinthisfile.Youalsoneedtodeclareallyouractivitieshere.
ActivityanActivityisaJavacontrollerclassthattypicallycorrespondsto
onescreeninyourapp
http://alvinalexander.com/android/androidcheatsheetmainconcepts 2/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
FragmentaFragmentisJavacontrollerthattypicallycorrespondstoa
widgetinascreen(orpossiblythefullscreen)
IntentyoulaunchnewactivitieswithIntents
Servicebackgroundservices,likenotifications
ContentProviderstbd
BroadcastIntent,BroadcastReceivertbd
RclassgeneratedforyoubytheAndroidbuildprocess
Moreimportantconcepts
ViewwidgetslikeTextView,ImageView,Button...
ViewGroupcontainersforotherviews
Layouts:FrameLayout,LinearLayout,RelativeLayout,TableLayout,
ListView,GridView
Menus(ActionBar,Toolbar)
Notificationssendnotificationsfromyourapptotheuserstabletor
phonenotificationscanalsobeforwardedtoAndroidWeardevices
Understandingscreendensitiesandsizes
dp,sp(andpx,in,mm,pt)
ldpi,mdpi,hdpi,xhdpi,xxhdpi
goodAndroidui/designercheatsheet:
petrnohejl.github.io/AndroidCheatsheetForGraphic
Designers/
EvenmoreimportantAndroidconcepts
AsyncTask,Handler
Timer,TimerTask
MediaPlayer,WebView,GPS
SharedPreferences,PreferenceManager
http://alvinalexander.com/android/androidcheatsheetmainconcepts 3/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
LocationManager
NeedtorequestpermissionsforcertainthingsinAndroidManifest.xml
Testingbestpractices(todo)
Nativecode(JNI)?
Ninepatchimages:astretchablebitmapimageAndroidautomatically
resizestoaccommodatetheviewsize
Themes:HoloLight,HoloDark,HoloLightwithdarkactionbar
Styles:youcancreatestylesandapplythemtowidgetsinamannersimilar
toCSS
Logging(Log.i,Log.e,etc.)
RESTservices,internetaccess
SQLdatabases(SQLite)
Androidfilesandfolders
AndroidManifest.xml
YoudescribeyourapplicationinAndroidManifest.xml
Asitsnameimplies,thisisanXMLconfigurationfile
FoldersinanAndroidproject
src
res/drawablestaticimages
res/layoutlayoutfiles
res/menumenulayoutfiles
res/valuesstrings.xml
Activity
http://alvinalexander.com/android/androidcheatsheetmainconcepts 4/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
anActivityisacontrollerclass(intheMVCsense)
anActivitygenerallycorrespondstoanAndroidscreen
needtoaddeachActivitytoAndroidManifest.xml
youspecifythe"launcher"activityforyourclassinthe
AndroidManifest.xmlfile
allotheractivitiesarelaunchedwithIntents
TheActivitylifecycle
it'simportanttoknowtheAndroidAndroidlifecycle,i.e.,whichmethods
areavailable,andwhentheyarecalled
inmyownexperienceAndroidislikeDrupalorSenchainthatyou
implementpredefined"callback"methodstodoyourwork
anactivitycanbeinoneoffourstates(moreorless):
Activestarted,andrunningintheforeground
Pausedstarted,isrunningandvisible,butsomethingis
overlayingpartofthescreen
Stoppedstarted,running,buthiddenbyanotheractivity
theuserisusing
Deadactivitywasterminated,suchasduetoinsufficient
ram
Workingwithstatechanges
(Mostofthesenotescomefromthefreeversionofthebook,BusyCodersGuidetoAndroid
Development.)
Youneedtobeabletosaveyourapplicationinstancestatequicklyand
cheaply
Activitiescanbekilledoffatanytime,soyouhavetosavestatemoreoften
thanyoumightexpect
http://alvinalexander.com/android/androidcheatsheetmainconcepts 5/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
Thinkofthisprocessas"establishingabookmark,"sowhentheuser
returnsthestatewillbeastheyleftit
SavinginstancestateishandledbyonSaveInstanceState(Bundle)
ThedefaultimplementationofonSaveInstanceStatewill(probably)save
thingslikethemutablestateofwidgetsthatarebeingdisplayed,likethe
textinaTextView(butitwon'tsavewhetherornotaButtonisenabledor
disabled,or,asi'velearned,abackgroundimageonawidget)
YoucangetthatinstancestateinonCreate(Bundle)and
onRestoreInstanceState(Bundle)
Insomeactivitiesyouwon'thavetoimplementonSaveInstanceStateat
allthisdependsonyouractivityandwhatdataitneeds,etc.
TheActivityonCreatemethod
onCreateiscalledwhenanActivityiscreated
OScallsthismethod"aftertheActivityinstanceiscreatedbutbeforeit's
putonascreen"
thingsyoucan/shoulddointhismethodinclude:
inflatewidgets
putwidgetsonscreen
getreferencestowidgets
setlistenersonwidgets
connecttoexternaldatamodels
note:nevercallonCreateyourself
onCreateiscalledinthreesituations:
whentheactivityisfirststarted,onCreateiscalledwitha
nullparameter
iftheactivitywasrunningandthenkilled,onCreatewillbe
invokedwiththeBundleyousavedwithacallto
onSaveInstanceState
http://alvinalexander.com/android/androidcheatsheetmainconcepts 6/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
whenthedeviceorientationchangesandyouhave
accountedforthatwithdifferentlayouts
setContentViewmethod
youwilloftencallsetContentViewinyouronCreatemethods
setContentViewinflatesalayoutandputsitonscreen
onDestroy
TheonDestroymethodmaybecalled:
whentheactivityisshuttingdown,becausetheactivitycalledfinish()
onDestroyismostlyusedforcleanly/properlyreleasingresourcesyou
createdinonCreate
becauseAndroidshutitdown(suchaswhenneedingram)
note:onDestroymaynotgetcallediftheneedforramisurgent.
onStart,onRestart,onStop
onStartiscalled(a)whenanactivityisfirstlaunched,or(b)whenit's
broughtbacktotheforegroundafterhavingbeenhidden
onRestartiscalledwhentheactivityisstoppedandisnowrestarting(just
afteronStart)
onStopiscalledwhentheactivityisabouttobestopped
onPauseandonResume
onPause:
onPauseiscalledwhentheuseristakenawayfromyouractivity,suchas
thestartingofanotheractivity
http://alvinalexander.com/android/androidcheatsheetmainconcepts 7/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
ifyouhaveresourceslockedup,releasethemhere(backgroundthreads,
camera,etc.).
onResume:
onResumeiscalledjustbeforeyouractivitycomestotheforeground,either
after:
initiallaunch
beingrestartedfromastoppedstate
afterapopupdialogwasshown
onResumeisagoodplacetorefreshtheUI,suchaswhenpollingaservice,
orifapopupdialogaffectstheview,etc.
Bundle
aBundleispassedintotheonCreatemethod
asyou'llsee,it'salsopassedintootherAndroidlifecyclemethods
aBundleisamap/dictionarydatastructurethatmapskeystovalues
(key/valuepairs)
aBundlecancontainthesavedstateofyourviews(amongotherthings)
youcansaveadditionaldatatoabundleandthenreaditbacklater
hasmethodslikeputInt,putSerializable,getInt,etc.
Fragmentclass
likeanActivity,aFragmentisacontrollerclass
fragmentswereintroducedinAndroid3.0whentheybegantosupport
tablets
tabletsrequiredmorecomplicated/flexiblelayouts,andfragmentswere
thesolution
http://alvinalexander.com/android/androidcheatsheetmainconcepts 8/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
fragmentsletyoucreatesmallwidgetsthatyoucanplugintolargerviews
saidanotherway,fragmentshelpseparatetheuiintobuildingblocks
usuallyafragmentmanagesaui,orpartofaui
anactivity'sviewcontainsaplacewhereafragmentwillbeinserted
anactivityissaidto"host"afragmentbyprovidingaspot
initsviewwherethefragmentcanplaceitsview
anactivitymayhaveseveralplacesforfragments
anactivitycanreplaceonefragmentwithanotherfragment
theBigNerdbookoffersthisadvice:alwaysusefragments(AUF)
aFragmentcanusegetActivity()togetareferencetoitsActivity
fragmentsaremanagedbytheFragmentManagerofthehostingActivity
Layouts(Containers)
youcancreateyourUIviewsusingXMLorJavacode,butXMListhe
preferredapproach
ofcourseXMLlayoutsareverbose,butanicethingisthattheyworkwell
withtheAndroidStudiodesigner
AndroidStudioalsogivesyouhelpfulhintswhenyou'researchingfor
attributestocontrolyourviews(soit'snotlikeyouhavetomemorizeevery
possibleattribute)
widgetsinyourlayoutsaremanagedbyeitheranActivityoraFragment
Androidhasthefollowingtypesoflayouts(theremaybeafewmorei've
usedthesesofar):
LinearLayout
RelativeLayout
FrameLayout
ListView
GridView
http://alvinalexander.com/android/androidcheatsheetmainconcepts 9/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
LinearLayout
inaLinearLayout,widgetsandchildcontainersarelinedupineithera
columnorarow,likeaFlowLayoutinSwing
aLinearLayouthasfivemaincontrols:
orientation
fillmodel
weight
gravity
padding
RelativeLayout
aRelativeLayoutlaysoutwidgetsbasedontheirrelationshiptoother
widgetsinthecontainer
RelativeLayouthasmanyconfigurationoptionsthatletyouposition
widgetsrelativetoeachother,includingthesebooleanvalues:
android:layout_alignParentTopthewidget'stop
shouldalignwiththetopofthecontainer
android:layout_alignParentBottomthewidget's
bottomshouldalignwiththebottomofthecontainer
android:layout_alignParentLeftthewidget'sleftside
shouldalignwiththeleftsideofthecontainer
android:layout_alignParentRightthewidget'sright
sideshouldalignwiththerightsideofthecontainer
android:layout_centerHorizontalthewidgetshould
bepositionedhorizontallyatthecenterofthecontainer
android:layout_centerVerticalthewidgetshouldbe
positionedverticallyatthecenterofthecontainer
http://alvinalexander.com/android/androidcheatsheetmainconcepts 10/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
android:layout_centerInParentthewidgetshouldbe
positionedbothhorizontallyandverticallyatthecenterof
thecontainer
italsoletsyouspecifyawidget'spositionrelativetootherwidgets:
android:layout_abovethewidgetshouldbeplaced
abovethewidgetreferencedintheproperty
android:layout_belowthewidgetshouldbeplaced
belowthewidgetreferencedintheproperty
android:layout_toLeftOfthewidgetshouldbeplaced
totheleftofthewidgetreferencedintheproperty
android:layout_toRightOfthewidgetshouldbeplaced
totherightofthewidgetreferencedintheproperty
(therearemoreattributesthanthose.thosecamefromanoldversionofa
booktitled,"TheBusyCoder'sGuidetoAndroidDevelopment")
Commonattributesinlayouts
match_parenttheviewwillbeasbigasitsparent
wrap_contenttheviewwillbeasbigasitscontentsrequire
@+idtheactualidwillbeingen/R.java,insideapublicstaticfinal
classid{...
gravity
more(todo)...
UIComponents/Widgets
ActionBar
Dialogs
Toastsshortlivedpopupmessages
http://alvinalexander.com/android/androidcheatsheetmainconcepts 11/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
Menusdon'tusetheseanymore,usetheActionBar
Standardwidgetsare:
Button
TextView
EditTextinputfield
Checkbox
RadioButton,RadioGroup
ToggleButton
Spinner...
Picker(DatePicker,TimePicker)
Toast
aToastisashortlivedmessagethatappearsinalittlepopupwindow.
CreateaToastlikethis:
youuseToaststoshowmessagestousers,suchasindicatingthat
somethingwassaved.
ialsouseToastsfortestingnewcode,likethis:
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
Crime crime = (Crime)(getListAdapter()).getItem(position);
Toast.makeText(getActivity(), "Click!", Toast.LENGTH_SHORT).show();
}
http://alvinalexander.com/android/androidcheatsheetmainconcepts 12/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
youcansetthegravityonaToast:
...Toastt=Toast.makeText(getActivity(),"Click!",Toast.LENGTH_LONG)
t.setGravity(Gravity.TOP,0,0)t.show()...
ActionBar
theActionBarwasintroducedinAndroid3.0
itletsyouputbutton/iconcontrolsonyourviews.atypicalbuttonona
ListViewisan"add"button,toletyouaddanewitem
theActionBarisstillsupported,butithinkit'sbeingreplacedbyaToolbar
youusedtohavetouseanActionBarActivitytouseanActionBar,butyou
don'thavetodothatanymore(asofVersion?(todo))
Intents
youuseanIntenttolaunchotheractivities
here'sasimpleexample:
here'sanotherexamplewhereipassan"extra"whenstartinganew
Activity:
Androidcommandline
http://alvinalexander.com/android/androidcheatsheetmainconcepts 13/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
I'mprettyweakontheAndroidcommandlinerightnow,soI'lljustlistafewofthe
commandsIhaveused:
adb logcat
adb shell
adb push image1.jpg /data/data/com.alvinalexander.myapp/files
IseeAndroidStudiorunsomeofthefollowingcommands.Itusesacommandlikethisto
installanewversionofmyappontotheemulatororphysicaldeviceIusefortesting:
pm install -r "/data/local/tmp/com.bignerdranch.android.criminalintent09"
Codesnippets
ThiscodeshowshowtodeterminewhichiteminaListViewwasselected:
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
Crime crime = (Crime)(getListAdapter()).getItem(position);
Toast.makeText(getActivity(), "Click!", Toast.LENGTH_SHORT).show();
}
Asshown,thiscodeshowsonewaytoshowaToastmessage:
category: android
tags: toast summary notes fragment cheatsheet android activity
related
http://alvinalexander.com/android/androidcheatsheetmainconcepts 14/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
AndroidfragmentsHowtogetanActivitywidget
SourcecodeforanAndroidAsyncTask(RESTclient)example
HowtoaccessanAndroidMenuItemfromaJavaActivityorFragment
SourcecodeforanAndroidViewPagerexample(ActivityandFragment)
AJavamethodtologAndroidmemoryuse
AndroidToastsyntaxexamples
booksivewritten
whatsnew
BlueOrigininflightcrewcapsuleescapetest
Foolishmortalsisagenderneutralformofaddress
Acceptingthejustthisofasituation
JoyfulDiscipline
Mastcellactivationdiseasevshistamineintolerance(differences)
MattCasseltalkingaboutBillBelichick
http://alvinalexander.com/android/androidcheatsheetmainconcepts 15/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
Addnewcomment
Yourname
Thecontentofthisfieldiskeptprivateandwillnotbeshownpublicly.
Homepage
Subject
Comment
Abouttextformats
AllowedHTMLtags:<em><strong><cite><code><ultype><olstarttype><li><pre>
Linesandparagraphsbreakautomatically.
Bysubmittingthisform,youaccepttheMollomprivacypolicy.
Save Preview
http://alvinalexander.com/android/androidcheatsheetmainconcepts 16/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
Links:
frontpagemeontwittersearchprivacy
java
javaapplets
javafaqs
misccontent
javasourcecode
testprojects
lejos
Perl
perlfaqs
programs
perlrecipes
perltutorials
Unix
man(help)pages
unixbyexample
tutorials
sourcecode
warehouse
javaexamples
drupalexamples
misc
privacypolicy
terms&conditions
subscribe
unsubscribe
wincvstutorial
functionpoint
analysis(fpa)
fpatutorial
Other
mobilewebsite
rssfeed
myphotos
lifeinalaska
howisoldmybusiness
livingintalkeetna,alaska
mybookmarks
inspirationalquotes
sourcecodesnippets
http://alvinalexander.com/android/androidcheatsheetmainconcepts 17/18
10/7/2016 AnAndroidcheatsheet(mynotes,mainconcepts)|alvinalexander.com
http://alvinalexander.com/android/androidcheatsheetmainconcepts 18/18