Simple example of button event listening developed by Android

  • 2020-06-19 11:43:48
  • OfStack

An example of button event listener developed by Android is presented. Share to everybody for everybody reference. The details are as follows:

listener for event listening has the following ways:

1. Declare a common class, implement OnClickListener interface, and then in setOnClickListener of button, an object of new class.

2, use anonymous inner classes, direct


btn.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View arg0) {
 System.out.println(" Anonymous inner classes do event listening ");
  }
});

The difference between the two approaches is that one is regular class and the other is anonymous inner class. The advantage of anonymous inner classes is that you don't have to define a class elsewhere and then answer the question used here. Write the logic of the required class directly where it is used.

The advantage of the regular class is that it can be reused.

Sometimes you can have activity implement the OnClickListener interface directly and have it act as a listener. In this case, the parameter in setOnClickListener only needs to be written this.

Hopefully, this article has been helpful in your Android programming.


Related articles: