A post at another blog describes three ways to attach click listeners (for elements such as buttons in Android applications). The first, the “Old Java [Object Oriented] Way”, way retrieves the object (ie, Button), and sets the onClickListener by creating an anonymous object which is passed to the button object. As he points out, this can be expensive in terms of memory, and can make for sloppy code.
The second way, The Shared Listener, uses a shared onClickListener object among all the [button] objects. A switch statement is used within the listener to determine which [button] object was hit and act accordingly. This still has the disadvantage of needing to retrieve the Button objects and attach the listener to each.
The third (and preferred way), the Declarative Approach, makes use of a method in the Activity to act as a shared listener and attaching that method in the XML via the “android:onClick” attribute. This relieves the burden of grabbing all your buttons in code and assinging them the listener method.
The added benifit of NOT using the first approach, as mentioned in the linked blog post, is a reduction of package size and a reduction in source bloat. To test how much memory was saved, a skeleton application was created. It consisted of five buttons linking to different activities (the fifth button was actually the quit button). When coded the first way, that is grabbing the button objects and assigning an anonymous object, the package size was about 17.8 Kb. When coded the third way, that is using the shared method and “android:onClick” attribute, the package size was 17.0 Kb.
Thats an overall savings of about 40 lines of code and 0.8 Kb (~4.5%) of package size for the above example.