Android – 即使方法已经结束,监听器对象也不会被销毁的原因是什么?

huangapple go评论54阅读模式
英文:

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

问题

在安卓(Java)中,如果我在方法内部声明了任何变量/对象引用,那么在方法完成后它会从堆栈中移除。

但是,如果我在方法中注册了点击监听器,那么即使方法完成后也会如何调用它。

代码:

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

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) {
  }
}):

}

答案1

得分: 0

> 如果我在方法内声明了任何变量/对象引用,方法完成后会从堆栈中移除。\n
这是不正确的。如果你创建了任何对象,它们会保留在堆内存中,直到进行垃圾回收。如果有任何对它们的引用 - 例如,对存储的监听器的引用 - 那么它们会持续存在,直到这些引用消失。

英文:

> "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.

huangapple
  • 本文由 发表于 2020年9月3日 08:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63715097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定