Best way to handle events in Android [closed] Best way to handle events in Android [closed] android android

Best way to handle events in Android [closed]


Let me try to explain case by case:

Case# 1This way will create anonymous clases as much as you create buttons (every button will need new listener ), and its less readable and costly.

Case# 2Actually if you read the code behind this, you will find it use reflection to find your listener (method) of callback, and its less readable, and confuses other developers.

Case# 3This way is hard to navigate through, because you can't determine the type of the listener you are using with current button (I know eclipse will highlight the methods this are pointing at, but with huge code I think it will be hard to find).

Case# 4I think this is the best way to implement the listeners,easy to navigate to, more readable, one listener can handle all related events (and with using eclipse, just ctrl+click you can go to the listener), so I recommend this (am using only this way at work)

I hope this will help


  1. I like this method if I only have one or two of the listener in the class. Such as a listview's onItemClickListener. With multiple views, it does get very messy indeed.

  2. I don't use android:onClick at all, simply because I like to keep my code in my code.

  3. I like this when I have a few views to handle. However, I still like to keep my onClick() code sparse. It typically ends up being a switch by id, with groups of like views calling additional methods to handle, like handleDownVote() or similar. This way, all of my main "handling" calls are done in one place.

  4. I didn't know people did this. I suppose it gives a better ability to group like views than #3, but I never really thought about it. Maybe I'll give it a shot some time.

When it all comes down to it, though, this is a highly subjective question, because there's not really a "right" or "optimized" way to do it. As you can see, every answer so far has been different. No offense, but voting to close.


The best way to handle an OnClick event of a Button depends on few things:

1. no of buttons you have.

Ans: if you have only one button you can go with 1st approch of creating annonymoous class.but if you have multiple buttons it is not good to create multiple anonymous onClicklisteners. but to go with other options

2. memmory optimization

Ans: If you are Implementing the OnClickListener interface on the Activity class and passing a self reference to the Button than the onclick listener will keep the reference to that activity object so it will be heavy to keep the whole activity's object in it, so in this way a local variable with the OnClickListener type is more optimized way.

So overall the best practise is the create a local variable with the OnClickListener type is the best way to handle any type of events not only onClick events on Button.