代码之家  ›  专栏  ›  技术社区  ›  Jim

非空视图在侦听器中是否可以为其上下文提供空引用?

  •  0
  • Jim  · 技术社区  · 6 年前

    final View someView = ....;  
    
    // some code  
    someView.setOnClickListener(v -> {  
        if(someView == null) return;  
        Context context = someView.getContext();  
        // can context be null at this point?
    }); 
    

    视图是否可能有空值 Context 在某种程度上?

    1 回复  |  直到 6 年前
        1
  •  0
  •   guipivoto SadeghAlavizadeh    6 年前

    我的猜测是:如果View不为null,那么context就不能为null。

    正在检查的源代码 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() )如果视图不为空,则不能为空。