0% found this document useful (0 votes)
68 views4 pages

Android Adventures Events: Anonymous Class

The document discusses different approaches for handling events in Android applications. It explains that anonymous classes can be used to implement event interfaces and create an instance of the event handler in one step, without needing a separate class definition. This allows associating different event handlers with different UI elements. While implementing the interface in an Activity class works for a single handler, anonymous classes provide a more flexible way to handle events.
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)
68 views4 pages

Android Adventures Events: Anonymous Class

The document discusses different approaches for handling events in Android applications. It explains that anonymous classes can be used to implement event interfaces and create an instance of the event handler in one step, without needing a separate class definition. This allows associating different event handlers with different UI elements. While implementing the interface in an Activity class works for a single handler, anonymous classes provide a more flexible way to handle events.
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/ 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