Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring that a class implements OnClickListener vs. declaring it yourself?

Apologies for my title, I am having trouble properly articulating the problem.

I have seen OnCLickListener implemented in two ways. The first is done by signifying that your class implements OnCLickListener. The second accomplishes the task by having you declare it yourself.

Why in the first option can you simply put this as your setOnCLickListener argument, but in the second you must go through the trouble of creating the OnClickListener object yourself?

The first:

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:

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 

            }
});
like image 485
Dick Lucas Avatar asked Feb 16 '23 23:02

Dick Lucas


2 Answers

In the first method, you entire Activity class implements the OnClickListener interface. You can set the OnClickListener of every View to this, and receive all the click events in one method, where you can then filter them and act upon them.

The second method uses an anonymous inner class that implements the interface method. By using this approach, you receive events only for that particular View.

In the first method, your entire class uses one single instance of the OnClickListener, that is passed to all the Views you want to listen for clicks on.

The second method translates to:

Button.OnClickListener anonymous_listener = new Button.OnClickListener() { ... };
button.setOnClickListener(anonymous_listener);

Which is to say that it dynamically creates and stores a new OnClickListener instance when you use it.

like image 62
Shankari vatsalkumar Avatar answered Feb 27 '23 10:02

Shankari vatsalkumar


I usually do the first manner because it saves an object. But if you need to implement many listeners, then to keep code more organized and neat, you can consider the second manner.

like image 37
TieDad Avatar answered Feb 27 '23 09:02

TieDad