关于android:setSupportActionBar之后,getSupportActionBar可以为null吗?

Can getSupportActionBar be null right after setSupportActionBar?

即使我已经使用getSupportActionBar()设置了支持操作栏,我还是应该对getSupportActionBar()方法进行空检查吗?

onCreate()中,我有三行

1
2
3
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));

然后,Android Studio会给我警告

1
"Method invocation may produce java.lang.NullPointerException"

假设findViewById方法确实返回了有效的ToolBar对象,我是否仍需要对getSupportActionBar()方法进行空检查,还是忽略警告是否安全?


这可能会产生NullPointer异常。

您已经创建了一个新的工具栏对象,可以使用toolbar.setTitle(getIntent().getStringExtra(TITLE_KEY));设置标题。您需要先执行此操作,然后再调用setSupportActionBar(toolbar);

由于已设置的操作栏是工具栏,因此无需调用getSupportActionBar()。因此,您可以直接使用该对象来编辑工具栏。那快于getSupportActionBar();


我的建议是:-不要检查null,因为警告不是错误

您正在谈论的警告说"可能会产生"。它没有说"必将产生"。

但是如果要再次确认,可以检查是否为空


否,您不应该对此进行检查。因为如果假设失败(例如,如果findViewById(R.id.toolbar)由于在项目的另一个文件中引入了错误而开始返回null),则您确实希望引发NullPointerException,因此在测试时很容易找到错误。铅>

换句话说:我认为,最好的方法是快速失败。

我的代码如下所示,并带有使警告消失的注释:

1
2
3
//noinspection ConstantConditions: Action bar should always be present. If not, we prefer a NullPointerException here.
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

为避免出现此警告,您始终可以检查ActionBar对象是否为空。

1
2
3
4
5
ActionBar mActionBar = getSupportActionBar();

    if (mActionBar != null) {
        mActionBar.setTitle(getIntent().getStringExtra(TITLE_KEY));
    }