7

I'm new in Android dev. I read some books about it. And all authors strongly recommend to use anonymous classes instead of class redefinition.

They say that

TextView txtTitle;
...
txtTitle.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {

   }
});

better than

   txtTitle.setOnClickListener(new MyOnClickListener(position));
   ...

private class MyOnClickListener implements OnClickListener{
...
}

Can anybody explain me why?

Ofc, if I will use redefinition class for many different object this will be the problem for modification.

But if I use my own class only for specific object, so logic of my class will not strongly change, can I use it? Or should I use anonymous class?

ShreeshaDas
  • 2,042
  • 2
  • 17
  • 36
  • 2
    No reason in particular, except that it avoids multiplying classes, and the scope of the anonymous class gives you access to the content of the including class. – njzk2 Oct 09 '13 at 07:26
  • But my MyOnClickListener has access to all variables too =/ – Suvitruf - Andrei Apanasik Oct 09 '13 at 07:33
  • @njzk2 quite the contrary, when you use new OnClickListener you de facto create a new class, try to do it 5 times in some class and see 5 inner classes in the comipler out folder – pskink Oct 09 '13 at 07:43
  • @pskink : my formulation is incorrect. I mean that it avoids multiplying java files, which can be bad for organisation, in particular if they are very specialized. Of course, when applicable, I'm all for factorization. – njzk2 Oct 09 '13 at 07:55

2 Answers2

11

Anonymous class will have access to the final outer variables, so it might be more convienient to use this. For instance:

 final String x = "123";
 Button button = (Button) findViewById(R.id.button);
 button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
                 // You can acces "x" here.
        }
 });

In addition, it's the question of the coding style. Using anonymous can lead to the code which is more verbose but, at the same time, a little bit easier to follow.

Also, non-anonymous class can be instantiated in multiple places.

kamituel
  • 34,606
  • 6
  • 81
  • 98
3

why not to implement OnClickListener in your Activity class?

class MyActivity extends Activity implements OnClickListener
pskink
  • 23,874
  • 6
  • 66
  • 77