是否建议在每次findViewById调用时检查视图是否为null? [英] Is it recommended to check view for null with every findViewById call?

查看:148
本文介绍了是否建议在每次findViewById调用时检查视图是否为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用findViewById扩展元素时,Android Studio始终警告我,我的扩展视图可能返回null

When inflating an element with findViewById, Android Studio always warns me that my inflated view may return null

View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);

并建议我用空检查对语句做环绕操作:

and suggests I do something like surround with my statement with a null check:

if (v != null) {
    mGridView = (GridView)v.findViewById(R.id.gridView);
}

是否建议在填充元素之前总是进行上述空检查?

Is it recommended to always do the mentioned null check before inflating an element?

编辑:添加皮棉图片

推荐答案

如果您确定所传递的ID在应用程序上下文中确实存在,则可以忽略此警告并继续执行代码.那么最好在访问此视图中的元素之前进行空检查,因为

You can ignore this warning and move ahead with your code if you are sure that the id you are passing does exist within your applications context, if you are not sure then its better to do a null check before accessing the elements in this view because

     View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);

在"R.layout.fragment_photo_gallery"不正确或无效的渲染环v为null的情况下返回null.

will return null in case "R.layout.fragment_photo_gallery" is incorrect or invalid renderring v as null .

这样尝试

     mGridView = (GridView)v.findViewById(R.id.gridView);

可能会导致空指针异常

这篇关于是否建议在每次findViewById调用时检查视图是否为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆