View.OnClickListener () - function or interface

Is View.OnClickListener () a function or interface? When we try to set the onclicklistener () method in android, we use the new View.OnClickListener (), and it turns me on there, as far as I know,

  • we do not need to initialize the class object containing the static inorder method in order to use these methods. Why are we doing this?
  • When we use inorder tools to implement an interface, we do not invoke static methods on the interface.

So can someone tell me why we do:

  • new View.OnClickListener (), to use the onclick () method?
  • Why do we use () with View.OnClickListener if it is an interface?

Thanks for your reply..

+6
source share
2 answers

I'm not sure I understand what you are writing about static methods. View.OnClickListener is the interface: http://developer.android.com/reference/android/view/View.OnClickListener.html

To set a click listener in a view, you pass an instance that implements the OnClickListerner interface: http://developer.android.com/reference/android/view/View.html#setOnClickListener(android.view.View.OnClickListener)

The most common way to do this in android is to define an anonymous inner class ( http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html ) that implements OnClickListener, e.g.

myView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Handle view click here } }); 

The above code specifies an anonymous inner class and instantiates it. This is equivalent to first defining a class that implements View.OnClickListener (if defined in one class)

 class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { // Handle view click here } } 

And later, using this

 MyOnClickListener listener = new MyOnClickListener(); myView.setOnClickListener(listener); 
+14
source

enter image description here

Code example

Inside it works something like this

 public class MyView{ public stinterface MyInterface{ public void myOnClick(View view); } } public class MyButton{ View view; public void setOnClicker(MyInterface onClicker) { onClicker.myOnClick(view); } } public class MyExample{ public void method(){ MyButton myButton = new MyButton(); myButton.setOnClicker(new MyInterface() { @Override public void myOnClick(View view) { } }); } } 
+1
source

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


All Articles