I am a .NET mobile developer and since i started working with android, i noticed that the only way i can store my event handlers of the views is through the activity file or by creating a class to hold all these event listeners. Can someone suggest best way that i can do to have the least clutter and store all the event handlers accordingly?
Share
A bit subjective as “clutter” depends on how efficient you are at implementing your event handlers and how complex your app is.
For instance I’ve seen example code here on SO like…
In each case an anonymous listener for each individual
Buttonoften performing a very similar function (start activity 1, start activity 2….). The cleanest way would be to implementView.OnClickListeneron theActivityitself and then use……(and so on for each
Button) then get the resource id of theViewpassed in to the listener to identify what was clicked and what needs to be done. It amazes me how many people don’t get that.As for creating a separate class (or classes) to hold listeners, that gets tricky depending on how many activities you have going on. Maintaining the listeners separately has two downsides.
Firstly if you don’t go with the model of having an
Activityuse anonymous listeners or implement the listener directly, that suggests you’ll have a whole load of activities (which may be extended at some point) using your ‘helper’ class listeners. Each time you extend yourActivityyou need to make sure the separate class is updated to cope with it – potentially an out of sight, out of mind problem where you want something new from anActivitywhich your ‘generic’ listener doesn’t handle.The second potential problem is in the way Android works (depending on your app). An Android
Activityis meant to be modular – if it displays photos or images or documents of a particular format then it should be as self-contained as possible. Having a separate class with a multitude of listeners in means that a very simpleActivitymeant to do a very simple task ends up loading a bloat of a class (or classes) which contains a whole load of listeners which aren’t relevant.Stick with simple – optimise the listeners for each
Activityand keep them self-contained. If you feel there’s any duplication going on, define your own base classes and extend from there.