Can getSupportActionBar be null right after setSupportActionBar?
即使我已经使用
在
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方法确实返回了有效的
这可能会产生NullPointer异常。
您已经创建了一个新的工具栏对象,可以使用
由于已设置的操作栏是工具栏,因此无需调用
我的建议是:-不要检查null,因为警告不是错误
您正在谈论的警告说"可能会产生"。它没有说"必将产生"。
但是如果要再次确认,可以检查是否为空
否,您不应该对此进行检查。因为如果假设失败(例如,如果
换句话说:我认为,最好的方法是快速失败。
我的代码如下所示,并带有使警告消失的注释:
1 2 3 | //noinspection ConstantConditions: Action bar should always be present. If not, we prefer a NullPointerException here. getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); |
为避免出现此警告,您始终可以检查
1 2 3 4 5 | ActionBar mActionBar = getSupportActionBar(); if (mActionBar != null) { mActionBar.setTitle(getIntent().getStringExtra(TITLE_KEY)); } |