英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论