Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

why not to implement OnClickListener in your Activity class?

class MyActivity extends Activity implements OnClickListener
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top