Search code examples
javaandroidandroid-activity

Android - How listener object is not destroyed even after the method is finished?


In android (java), If I declared any variables/objects reference inside the method, it is removed from stack after the method is finished.

But if I register click listener in a method, then how it is invoked even after the method is finished.

Code:

public void init() {
Button btn = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  }
}):

}

Solution

  • "If I declared any variables/objects reference inside the method, it is removed from stack after the method is finished."

    This is incorrect. If you create any objects, they stay on the heap until they're garbage collected. If there are any references to them -- say, a reference to a stored listener -- then they last until those references go away.