Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use anonymous classes in Android instead of class redefinition?

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?

like image 872
Suvitruf - Andrei Apanasik Avatar asked Oct 09 '13 07:10

Suvitruf - Andrei Apanasik


2 Answers

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.

like image 98
kamituel Avatar answered Dec 01 '22 11:12

kamituel


why not to implement OnClickListener in your Activity class?

class MyActivity extends Activity implements OnClickListener
like image 33
pskink Avatar answered Dec 01 '22 11:12

pskink