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?
The choice depends entirely the way you plan to use the class, each method is valid and has their corresponding strengths and weaknesses:
onClick()
function, which may or may not become an organizational mess. onClick()
functions and use them in more logical methods.But I would like to present Method 3, an anonymous callback:
public class MyActivity extends Activity {
OnClickListener myClickListener1 = new OnClickListener() {
public void onClick(View v) {
..
}
}
OnClickListener myClickListener2 = new OnClickListener() {...}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
view.setOnClickListener(myClickListener1);
}
}
Notice that unlike Method 2, I did not create a custom class. I would avoid creating a new custom class unless you are going to add more functionality, keep local variables, or otherwise modify the basic function of an OnClickListener.
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 Surface
callbacks 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With