【问题标题】:Can a non-null view have a null reference for its context in a listener?非空视图可以在侦听器中对其上下文有空引用吗?
【发布时间】:2019-06-30 13:03:34
【问题描述】:
假设代码如下:
final View someView = ....;
// some code
someView.setOnClickListener(v -> {
if(someView == null) return;
Context context = someView.getContext();
// can context be null at this point?
});
视图是否有可能在某些流程中有一个空的Context?
【问题讨论】:
标签:
android
android-view
android-context
【解决方案1】:
我的猜测:如果 View 不为空,我认为上下文不能为空。
查看View.java的源码,可以看到:
public class View {
public View(Context context) {
mContext = context;
}
public final Context getContext() {
return mContext;
}
}
如你所见,mContext 在构造函数中被初始化并且它的引用没有改变(mContext 引用没有更新).. 它总是指向在构造函数中接收到的引用。
此外,getContext() 是最终的。因此,它不能被覆盖以确保getContext() 将始终执行上面的代码。
如果您尝试创建一个传递空指针的视图(如View someView = new View(null)),您的应用程序将因其他原因崩溃...因此,如果视图不是,mContext(和getContext())不能为空空。