声明 'FLAG_ACTIVITY_NO_ANIMATION' 后出现 NullPointerException 警告

NullPointerException warning after declaring 'FLAG_ACTIVITY_NO_ANIMATION'

为操作栏中的后退箭头定义FLAG_ACTIVITY_NO_ANIMATION 以在单击工具栏后退箭头时更正为动画后,返回警告。消除此警告的最佳方法是什么?

Method invocation 'addFlags' may produce 'java.lang.NullPointerException'

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        final Intent intent = getParentActivityIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

来自 getParentActivityIntent 的文档:

@return: a new Intent targeting the defined parent of this activity or null if there is no valid parent.

此方法 return 只有在没有父 Activity 时才为空,因此他们为 return 值标记了 @Nullable 注释。这就是你收到警告的原因。

如果您确定在清单中定义了父级 Activity,则不必担心 NullPointerException,您可以抑制此警告。

要抑制,必须在方法中添加@SuppressWarnings("ConstantConditions")

最好在注释上方添加一条注释,解释您为何禁止警告。

将其包装到 if 意图中!= null。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        final Intent intent = getParentActivityIntent();
        if(intent != null){
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        }else{
          //Do some error handling.
        }
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}