To handle an event, there are 2 ways:
-
Implementing the callback interface, for example
public class A implements View.OnClickListener { public void onClick(View v) { .... } @Override protected void onCreate(Bundle savedInstanceState) { ... aboutLayout = (LinearLayout) findViewById(R.id.aboutLayout); aboutLayout.setOnClickListener(this); } } -
Creating an inner class which implement the callback interface
public class ActivityAbout { private class ViewClickListener implements View.OnClickListener { public void onClick(View v) { .. } } @Override protected void onCreate(Bundle savedInstanceState) { ... ViewClickListener listener = new ViewClickListener(); aboutLayout = (LinearLayout) findViewById(R.id.aboutLayout); aboutLayout.setOnClickListener(listener); } }
Which one is better?
I tend to use an inner class if either the code is very long (and needs to be organized or methodized), or if I plan to use the same code over and over. Even my
Surfacecallbacks are organized as inner classes, just for clarity’s sake.I use an anonymous class if the code is short and easy to handle (perhaps just one line within the event).
I only ever use the first implementation if the events are directly related to the class itself, and will never need other listeners attached to it. This is a very rare circumstance. (I also use it for simple debugging, but that’s kind of irrelevant here.)