在 Library 22 中用什么代替 getSupportActionBar()?
What to use instead of getSupportActionBar() in Library 22?
我的代码中有一行标记为黄色:
getSupportActionBar().setDisplayShowHomeEnabled(true);
安装 appcompat-v7:22.1 后显示提示:
"Method invocation may produce java.lang.nullpointerexception".
应该使用什么来代替 getSupportActionBar()
?
getSupportActionBar().setDisplayShowHomeEnabled(true);
应该说
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportActionBar() 可以 return null 所以你的提示告诉你这件事。
如果您要扩展具有操作栏的 Theme.AppCompat
或您自己调用了 setSupportActionBar(...)
,则调用 getSupportActionBar()
是安全的。
要绕过警告,请执行空检查或
assert getSupportActionBar() != null;
如果表达式不为真,将抛出异常。各有各的用处。
我找到了另一种方法,使用 AppCompatDelegate:
getDelegate().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
是否在样式中使用 NoActionBar
?验证您的 style.xml
或您的主题 if("NoActionBar") => nullpointer =D
我的代码中有一行标记为黄色:
getSupportActionBar().setDisplayShowHomeEnabled(true);
安装 appcompat-v7:22.1 后显示提示:
"Method invocation may produce java.lang.nullpointerexception".
应该使用什么来代替 getSupportActionBar()
?
getSupportActionBar().setDisplayShowHomeEnabled(true);
应该说
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportActionBar() 可以 return null 所以你的提示告诉你这件事。
如果您要扩展具有操作栏的 Theme.AppCompat
或您自己调用了 setSupportActionBar(...)
,则调用 getSupportActionBar()
是安全的。
要绕过警告,请执行空检查或
assert getSupportActionBar() != null;
如果表达式不为真,将抛出异常。各有各的用处。
我找到了另一种方法,使用 AppCompatDelegate:
getDelegate().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
是否在样式中使用 NoActionBar
?验证您的 style.xml
或您的主题 if("NoActionBar") => nullpointer =D