Understanding how to set a listener on a button in Android

By | June 8, 2017

There is a bit more to it when trying to create a button in Android and setting a listener to it. The new way hides a lot of the complexity but it also hides a lot of the understanding.
The “traditional” way was:

 btn = (Button)findViewById(R.id.firstButton);
 btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
      tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));

This can be a bit hard to understand when you first start learning about it. The key is to break it down.
setOnClickListener is a public method of the View class. (https://developer.android.com/reference/android/view/View.html)

A Button is a sub class of View (https://developer.android.com/reference/android/widget/Button.html) as you can see from below.

This means that for a Button object, btn you can do btn.setOnClickListener. So far so good?

The next question is what does setOnClickListener take as parameters/arguments if any? The answer, again from the docs above:

It takes a View.OnClickListener l.

However, View.OnClickListener is defined as a public static interface with 1 public method. onClick(View v). See the docs at: https://developer.android.com/reference/android/view/View.OnClickListener.html

Another way to understand this is graphically is:

Now because there are no methods implemented, (it’s just an interface), we cannot instantiate an object OnClickListener. So there are 2 options. You can “implement” this interface and then override it via:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// and then
public void onClick(View v) {

But this is tedious to do each time you want to set a click listener. Therefore, you can provide the implementation on the spot as shown above.

Ref: https://stackoverflow.com/questions/25803727/android-setonclicklistener-method-how-does-it-work

Leave a Reply

Your email address will not be published. Required fields are marked *