View.OnClickListener, can you explain?

Sorry if this question might be silly for you, but I'm new to Android programming and I can't plunge into the Java syntax.

Can you explain what happens with this line of code step by step?

View.OnClickListener ourOnClickListener = new View.OnClickListener() {
       @Override
       public void onClick(View v){
       ourMessage.setText("The button got tapped");
       }
   };
+4
source share
1 answer

The class Viewhas an interface, and it OnClickListener, it looks like this in the source View.java:

/**
* Interface definition for a callback to be invoked when a view is clicked.
*/
public interface OnClickListener {
    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    void onClick(View v);
}

Usually you should create a class and implement this interface:

public void MyClass implements View.OnClickListener {

  @Override
  public void onClick(View view) {
    // do stuff
  }
}

But sometimes you do not need this class in a separate file. Instead, you can create an anonymous inner class, this is like creating a new class in which only methods are specified from the specified interface:

new View.OnClickListener() {
       @Override
       public void onClick(View v){
           ourMessage.setText("The button got tapped");
       }
}

, View.OnClickListener.

, , . , :

public class MyClass {

  private int clicksCount = 0;

  private View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      clicksCount += 1;
    }
  }
}

clicksCount, MyClass , OnClickListener. - , final:

public void testMethod(final int canAccess, int cantAccess) {
  final String test = otherView.getText().toString();
  myView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      // Cannot access cantAccess, because it not final
      if (test.length == 0) { // can access
        // do something
      }
    }
}
+12

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


All Articles