3

Please explain why, in the below code (this) is used as argument to setOnClickListener()? I am new in coding if you could explain the total code I would be thankful.

public class MainActivity extends Appcomatactivity implements 
        View.OnClickListner {

  Textview textview;
  Button push_me, push_me2;

  protected void onCreate(bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.Layout.activity_main);
    textview = (Textview)findViewById(R.Id.Textview);
    push_me=(Button)findViewById(R.Id.pushmebutton);
    push_me2=(Button)findViewById(R.Id.pushmebutton2);

    // Why does below code use (this) as argument?
    push_me.setOnClickListener(this);
    push_me2.setOnClickListener(this);
  }
  // <...some activity methods...>

  // onclick method defined:
  public void onClick(View view) {
    switch(view.getid()) {
      case R.Id.pushmebutton:
        textview.setText("button 1 clicked");
        break;
      case R.id.pushmebutton2:
        textview.setText("button 2 clicked");
        break;
    }
  }
}
M. Prokhorov
  • 3,894
  • 25
  • 39
Raghu
  • 59
  • 1
  • 3
  • This will Help: https://stackoverflow.com/questions/29479647/setonclicklistener-vs-onclicklistener-vs-view-onclicklistener – Aj 27 Apr 04 '18 at 08:48
  • By implementing `View.OnClickListener` you are saying that `MainActivity` class can react to `click` events on some component. To make it do so, you have to register the `MainActivity` instance with the view, which is done by setting it into a View using that method. – M. Prokhorov Apr 04 '18 at 11:55

2 Answers2

3

Why is (this) used in setonclicklistner

Because your have implemented View.OnClickListener interface to your activity

View.OnClickListener Interface definition for a callback to be invoked when a view is clicked.

By using this push_me.setOnClickListener(this); you have registered click listener to your view

Nilabja
  • 4,206
  • 5
  • 27
  • 45
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
1

when we don't want to use anonymous class then we use this other way is to use anonymous inner class

//declaring OnClickListener as an object
private OnClickListener btnClick = new OnClickListener() {
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
}
};
//passing listener object to button
btn1.setOnClickListener(btnClick);

If there are multiple buttons which require same code to be executed on onClick event then you may define listener as an object and pass it to them.

Pawan Lakhotia
  • 385
  • 1
  • 10