Declare a class to implement OnClickListener or declare it yourself?
Apologies for my title, I couldn’t spell the issue properly.
I’ve seen OnCLickListener
it implemented in two ways. The first is done by representing your class implementation OnCLickListener
. The second completes the task by letting you declare it yourself.
Why in the first option you can simply take this
as your setOnCLickListener
argument, but in the second option you have to go through creating OnClickListener< 的麻烦
against yourself?
The first one:
public class WidgetConfig extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
Button b = (Button)findViewById(R.id.bwidgetconfig);
b.setOnClickListener(this);
}
//onClick defined outside of the onCreate
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
The second one:
public class WidgetConfig extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
Button b = (Button)findViewById(R.id.bwidgetconfig);
b.setOnClickListener(bListener);
}
private Button bListener = new OnClickListener(){
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//TO-DO
}
});
Solution
In the first method, you implement an interface for your entire activity class OnClickListener
. You can set each View’s OnClickListener
to this and receive all click events in one method, where you can then filter them and manipulate them.
The second method uses an anonymous inner class that implements the interface method. By using this method, you will only receive events for that particular View.
In the first method, your entire class uses OnClickListener
an instance that is passed to all the Views that you want to listen for clicks.
The second method translates to:
Button.OnClickListener anonymous_listener = new Button.OnClickListener() { ... };
button.setOnClickListener(anonymous_listener);
That is, when you use it, it dynamically creates and stores a new OnClickListener
instance.