views:

56

answers:

1

Hi,

I am writing my first Android application and have some problems with handing around context objects. A lot of methods/constructors seem to require the current context (activity) which causes me some problems in my action listeners. Instead of having all my listeners and handlers as anonymous classes in the activity class I have created classes for each event I would like to handle. For example a button buttonRegister would be initialized as:

buttonRegister.setOnClickListener(new RegisterButtonClickAction());

However when doing this I have no access to the current context object inside my listener. I could hand over a current context as a constructor parameter but I am not sure whether this is the best choice. What is the "best practice" for creating handler/listeners in Android or working with context objects in general?

Thanks,
b3n

A: 

Just pass the current Context in the handler's constructor.

Tho using event handlers like these can get messy. Most of the time, when you're handling some event - like pushing a button - then you want to change the states of other variables that are in your Activity (change some data structures, UI elements like TextView, whatever). If the event handler class is outside, you also have to provide references for the objects it can modify, possibly in it's contructor.

I usually just use anonymous, or at least inner classes, I think that's much more cleaner and simpler.

Scythe
Thanks, it makes sense even though I wanted to avoid huge classes with all sorts of event handling logic and split it up a little.
b3n