You are on page 1of 4

16/5/2017 Android Adventures - Events

AndroidAdventuresEvents
WrittenbyMikeJames
Thursday,20October2016

ArticleIndex
AndroidAdventuresEvents
Implementtheinterfaceintheactivity
AnonymousClass

Page3of3

Anonymousclass
Javahasanonymousclassesforjustthesituationwearetrying
tosolve.Itletsyoueffectivelycreateanobject,i.e.aninstance
ofaclass,withouthavingtoexplicitlycreateaclass.
Thatisadirectmethodofcreatingtheeventobject.Insteadof
Event Class -> Event Object -> Set As Listener
wejustgostraightto
Event Object -> Set As Listener
Theonlydownsideofusinganonymousclassesisthatyou
can'tcreateasecondinstanceoftheclassthisisashortcut
wayofcreatingoneinstanceofanobject.
Youcreateananonymousclassbywritingthesamecodeyou
wouldneedtocreateaninstanceofanexistingclassbutyou
add{blockofcode}followingittodefinethenewmethodsofthe
newclassyouarecreating.Theresultisaninstanceofthenew
class.
ForexamplesupposeyouhaveaclasscalledHellothatdisplays
ahelloworldmessageandyouwantanobjectthatdoes
everythingthatHellodoesbutwiththeadditionofagoodbye
method.NormallyyouwouldcreateaLeaveclassthatinherits
fromHelloanddefinesthenewmethodandthencreatean
instanceofLeave.Insteadyoucanwrite
Hello leave = new Hello(){
goodbye(){
display message;
}
}
ThiscreateaninstanceofHellothathasalloftheHellomethods
plusthenewgoodbyemethod.Noticethatleaveisanobjectand
notaclassandyoucancallmethodssuchasleave.goodbye()
atonce.Youhaveavoidedhavingtocreateanewclassjustto
createoneinstanceofit.Iftheclassyouareextendinghasa
constructorthatneedsparameterssimplycalltheconstructorin
theusualwayandaddthecodethatextendstheclass

http://www.i-programmer.info/programming/android/10051-android-adventures-events.html?start=2 1/4
16/5/2017 Android Adventures - Events

immediatelyafter.
Sotocreateaninstanceofananonymousclassbasedonan
existingclassyousimplystartoffbycreatinganewinstanceof
theclassandthentagon,incurlybrackets,allthemethodsyou
wanttoadd.
Inthecaseofaneventhandleryoucantakeaninterfaceand
implementitasifitwasaclassandcreateaninstanceinone
go.Thisisjustshorthand,syntacticsugarifyoulike,forwhatwe
didintheprevioussections.
Forexample:
MyInterfaceinstance=newMyInterface{
functions which are needed to
implementMyInterface
}
Thiscreatesaninstanceoftheimplementation
ofMyInterfacethatiscontainedwithinthebraces.Noneedto
defineaclasstogetaninstanceofit.
SoforouronClickeventhandlerusingananonymousclass
makesthingsmucheasierbecausewedon'tneedaseparate
filetoholdthenewclassandinfactwedon'tevenneedthenew
classjust:
View.OnClickListenerListener=
new View.OnClickListener(){
@Override
public voidonClick(View view) {
//Implement event handling
}
}
andtheinstanceofourcustomlistenercompletewith
ouronClickeventhandlerisreadytobeusedasbefore:
button.setOnClickListener(Listener);
Ofcourseyoucansavetheuseofavariableandsimplyusethe
anonymousclassinthesetOnClickListenerasin:
button.setOnClickListener(
new View.OnClickListener() {
@Override
public voidonClick(View view) {
//Implement event handling
}
});
WenolonghavetousetheListenervariablebutthecostisthat
weneedtobecarefultoremembertoclosethefunctioncallwith
arightparenthesis.
ThereallygoodnewsisthatAndroidStudiowillhelpyoucreate
theanonymousclass.IfyoustarttotypeinOnClickListenerit
willprovideyouwithoptionstocompletethenameandyoucan
selectOnClickListeneritwillthengeneratedummyfunctions
http://www.i-programmer.info/programming/android/10051-android-adventures-events.html?start=2 2/4
16/5/2017 Android Adventures - Events

forallofthemethodsdefinedintheinterface.


Allyouhavetodoisprovidethecodeinthebodyofeachofthe
functionsthatdoeswhatyouwant.
Thereisonesmallmysterythatwehavetodealwitheven
thoughitisn'treallyuseful.AndroidStudiousescodefoldingto
hidethedetailsofblocksofcodefromyou.Usuallythisisuseful
butinthecaseofanonymousclassesitcanbeconfusing.
Forexampleifyoutypeinthecodeabovethatsets
theonClickListenertheninfoldedviewthecodereads:

Thisisexactlyhowyouwouldwritethesamecodeusinga
lambda.Thepointisthat,asalreadymentioned,youcan'tuse
lambdasinJava7whichiswhatAndroiduses.Sothiswayof
representingthecodeispurelyforlookingat.Ifyouclickthe
small+buttontotheleftyouwillseethecodeexpandandyou
willseethefullversion.
IfyoucoulduselambdasinAndroidcodethiswouldbethebest
waytoimplementaneventhandlerbutyoucan'tandsoitis
annoyingthatAndroidStudiotauntsyouwiththisbetterwayof
writinganeventhandleryouwillbeabletowritethisinthe
futureandyoucanwritecodethiswaynowifyouareprepared
todosomereconfiguringandgiveupinstantrun.
Myadviceistowriteeventhandlersinoneofthreetraditional
waysandwaitforlambdastocometoAndroidStudio.

WhichApproachToEventHandlersShould
YouUse?
Inpracticetheanonymousclassapproachseemstobethebest
because,whileitisalittlemorecomplicateditiscompletely
general.UsingtheActivitytoimplementtheinterfacefailswhen
youneeddifferenteventhandlerslinkedtoeachcontrol.
Thatis,supposeyouhavethreebuttonsthenusinganonymous
classesyoucansetadifferenteventhandlertoeachbutton.If
youimplementtheeventhandlerintheActivitythenthesame
eventhandlerwillbeusedforallthreebuttonsandyoucodehas
totesttoseewhichbuttonhasbeenclicked.
Ofcourseanonymousclasseshavetheoppositeproblemto
implementingtheinterfaceintheActivity.Youcan'treusethe
http://www.i-programmer.info/programming/android/10051-android-adventures-events.html?start=2 3/4
16/5/2017 Android Adventures - Events

eventhandlerbecausethereisonlyoneinstanceofit.Thatisif
youwantthreedifferenteventhandlersoneforeachbuttonyou
havetowriteoutthecodethreetimestocreatethreeinstances.
Theanonymousclassapproachmakesadirectconnection
betweentheUIcomponentandtheeventhandlingcodeyouare
creating.YouonlyhavetolookatthesetListenerfunctioncallto
seethecodethathandlestheevent.
Inthissenseitisworththeextraeffortandistheoneusedin
therestofthisbook.IfyouwanttousetheXMLmethod
introducedearlierfortheonClickeventorimplementthe
interfaceintheactivityapproachthenthisshouldcauseno
problems.

Summary

InJavayoucan'tpassafunctiontosetupanevent
handleryouhavetopassanobject.
Eachtypeofeventhasitsowninterfacewhichisuseto
createanobjectwhichhasthemethodsneededforthe
event.
Themostdirectwaytocreateaneventhandleristo
createanewclassthatimplementstheinterfaceandthen
createaninstanceoftheclasstohandletheevent.
Toavoidtheproblemswithhavingtocreateanewclass
foreacheventhandlerJavaintroducedtheanonymous
class.Youcanuseananonymousclasstoimplementan
eventinterfaceandcreateaninstanceofitinonemove.
AlternativelyyoucanuseActivitytoimplementthe
interface.
Atthemomentyoucan'teasilyuselambdaexpressionsto
implementaneventhandler.

http://www.i-programmer.info/programming/android/10051-android-adventures-events.html?start=2 4/4

You might also like