Home > OS >  How can we use new View.OnClickListener directly when OnCLickListener is not static
How can we use new View.OnClickListener directly when OnCLickListener is not static

Time:07-30

I was wondering one thing today. Whenever we are setting up a ClickListener, we run this code.

tv.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

  }
});

I Opened the View Class and saw the OnClickListener interface and found that it is not static. The method is like this:

public interface OnClickListener {
  /**
   * Called when a view has been clicked.
   *
   * @param v The view that was clicked.
   */
  void onClick(View v);
}

Then how are we able to access OnClickListener method directly by using class name?

CodePudding user response:

For java, "A nested interface is implicitly static." jls (9.1.1.3)

CodePudding user response:

You can implement class View.OnClickListener and then you will able to Override its method just like shown below :

public class YourActivity implements View.OnClickListener {
  @Override
  public void onClick(View v) {

  }
}
  • Related