Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does setOnclickListner(this) work?

Tags:

android

this

There are multiple ways to register callbacks when a Button is clicked. If I go by the following way:

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Toast.makeText(this, "Hello onCLick", Toast.LENGTH_SHORT).show();
}
}

I don't understand how the method setOnClickListener(this) identifies that it should call onClick() method?

like image 774
vanguard69 Avatar asked Dec 01 '25 08:12

vanguard69


1 Answers

This refers to the activity. Because the Activity implements an OnClickListener calling button.setOnClickListener(this) gives the onClickListener that the Activity implements to setOnClickListener.

I recommend you look up info about implementing interfaces in Java if you want tot know more about this practise.

like image 102
nourikhalass Avatar answered Dec 04 '25 00:12

nourikhalass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!