android - Fragment 的 onResume() 中的 getview()

标签 android android-fragments nullpointerexception

我在 fragment 的 onResume() 中有以下代码。

getView().setFocusableInTouchMode(true);
getView().requestFocus();

由于此代码是从 onResume() 内部调用的,因此我没有使用 null 检查。

所以,我不会像下面这样写:

if(getView() != null){
getView().setFocusableInTouchMode(true);
getView().requestFocus();
}

我的问题是:在这种情况下可以跳过空检查吗?还是应该向空检查添加代码?

在什么情况下,getview() 在 onResume() 中将为 null?

最佳答案

根据this lifecycle diagramonResume 中的 getView() 永远不应该为 null。然而,在这种情况下,采取防御措施并不会真正造成伤害。不过,我可能会将 View 拉入本地引用,而不是调用 getView() 三次。

View view = getView();
if (view != null) {
    view.setFocusableInTouchMode(true);
    view.requestFocus();
}

关于android - Fragment 的 onResume() 中的 getview(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036061/

相关文章:

java - 我的 Searchview 不起作用/给出 NullPointerException setSearchableInfo

android - 为 Android 中的 facebook 集成生成调试 key

java - Android:如何使用 grantUriPermission 来创建和发送带有位图附件的电子邮件

android - "table or subquery expected, got "Android Room 错误

android - java.lang.IllegalArgumentException : No view found for 异常

android - 从日历中选择日期并将其显示在 TextView 中的最佳方法

android - 为什么两个不同的应用程序使用 aviary sdk 没有安装在同一台设备上?

android - 等到 fragment 被添加到 UI

java - 从 Session 变量中检索 ArrayList

Java.NullPointerException 为空