如何告诉Android Studio null检查已经完成



如何在Android Studio中配置Assert/Check方法?

我使用Mosby MVP框架,在presenter中我经常使用这个模式:

if (isViewAttached()) {
    getView().someViewMethod();
}

getView()标记为@Nullable,所以Android Studio显示我警告method invocation 'someViewMethod' could produce NullPointerException。它不明白我之前检查过它。

我找到了关于配置断言/检查方法的绝妙答案:https://stackoverflow.com/a/19319326/1263771

但是不能在新的Android Studio中这样做,因为它有不同的设置界面。那么,如何在最后一个工作室中做到这一点呢?

目前最简单的方法是使用

V view = getView();
if (view != null){ // instead of isViewAttached()
   ...
}

@Nullable注释很可能会在Mosby 3.0的下一个主要版本中被删除

完全同意@tse。那是一个聪明的答案,但已经过时了。

但我找到了一个有用的解决方案。你必须将isViewAttached()方法设置为static并将view作为参数发送。

protected static boolean isViewAttached(final View view) {
    return view != null && view.isAttached();
}
if (isViewAttached(getView())) {
   getView().someViewMethod();
}

最新更新