Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use anonymous classes for OnClickListeners or inner named classes?

Tags:

java

android

I have lots of buttons in my Activity, I have the following questions:

  1. Should I create multiple inner anonymous classes for OnClickListeners for each button, like below:

    private View.OnClickListener mShuffleListener = new View.OnClickListener() {
        public void onClick(View v) {
            /// task to do
        }
    };
    
  2. Or should I go for a named inner class and add an if condition to check which click listener was called.

Which one is better to save memory resources?

like image 578
AAnkit Avatar asked Mar 13 '12 06:03

AAnkit


2 Answers

Which one is cool to save mem resources?

It will make hardly any difference. At most 1 word ... and that is comparing a static inner class with a (non-static) anonymous class. A saving as small as that is not worth the code readability / maintainability penalty, even (IMO) if you've got a hundreds of these buttons.

like image 108
Stephen C Avatar answered Oct 05 '22 05:10

Stephen C


There are three ways to handle event. Please have a look on the following link

http://tseng-blog.nge-web.net/blog/2009/02/14/implementing-listeners-in-your-android-java-application/

See the following to know the use of anonymous class and inner class

anonymous class

Use anonymous inner classes if you want the code not to be used anywhere else (this class is being used just here and nowhere else.)

inner class

inner class code can be used (if only by the class that created it if made private). If you see a named inner class, someone might think it'd be used in multiple places in the class.

like image 45
Sunil Kumar Sahoo Avatar answered Oct 05 '22 05:10

Sunil Kumar Sahoo