Creating an instance of the interface itself in Android

Here is the code

btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //... } }); 

where setOnClickListener looks like this:

 public void setOnClickListener(android.view.View.OnClickListener l) { /* compiled code */ } 

However, what is the new View.OnClickListener() itself? It turns out this is the interface:

 //View.class public static interface OnClickListener { void onClick(android.view.View view); } 

That is, here btn.setOnClickListener(new View.OnClickListener() .... I am creating an instance of the interface. No, this is not an instance of the class that implements this interface.

How to create an instance of the interface?

+4
source share
1 answer

Yes it is. This is an anonymous class that implements the interface. The onclick that comes after is the onclick implementation.

Try this as follows:

 View.OnClickListener listener=new View.OnClickListener() { public void onClick(View v) { //... } }; btn.setOnClickListener(listener); 

It may look more clear.

+4
source

Source: https://habr.com/ru/post/1490947/


All Articles