gpt4 book ai didi

android - post runnable 能否在运行它的 View 上获得空引用?

转载 作者:行者123 更新时间:2023-11-29 01:01:28 26 4
gpt4 key购买 nike

当我们注册点击监听器等作为常见做法时,我们会检查 View 是否仍然存在,例如

final View someView = ...;  
someView.setOnClickListener( (l) -> {
if(someView != null) {
// access view
}
});

因为在调用监听器时 View 可能已经丢失。
但在以下情况下:

View someView = ...;  
someView.post(() -> {
// can someView be null here?
});

最佳答案

其实可以的。如果您阅读 docs :

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

View 类中的post() 方法将简单地向MainThread 的MessageQueue 添加一个runnable。此 runnable 将在某个时候运行,如果您的 View (Activity)在此期间被破坏,则在该 runnable 中使用 someView 可能会导致内存泄漏(它可能为空)。即使 someView 被销毁,runnable 仍将保留对它的引用(空引用),并且只会在执行 run 方法后释放它。

关于android - post runnable 能否在运行它的 View 上获得空引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50857364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com