Android getActionBar() 返回 Null (AppCompat-v7 21)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26435231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getActionBar() returns Null (AppCompat-v7 21)
提问by user3184899
My app is crashing the minute I run it after I changed my AppCompat-v7 to 21.0.0 and Compiled with no problem.
在我将 AppCompat-v7 更改为 21.0.0 并且编译没有问题后,我的应用程序在我运行它的那一刻崩溃。
It gives me the error:
它给了我错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setIcon(int)' on a null object reference
on this line:
在这一行:
getActionBar().setIcon(R.drawable.ic_action_bar);
It works with AppCompat-v7 20.0.0, but not with 21.0.0.
它适用于 AppCompat-v7 20.0.0,但不适用于 21.0.0。
回答by CommonsWare
You need to call getSupportActionBar()
on an ActionBarActivity
. Do not call getActionBar()
-- that is not available on older devices, and for the new r21 edition of appcompat-v7
, I would expect it to return null
all the time, as the new ActionBarActivity
disables and replaces the system action bar.
您需要调用getSupportActionBar()
一个ActionBarActivity
. 不要调用getActionBar()
- 这在旧设备上不可用,对于新的 r21 版本appcompat-v7
,我希望它一直返回null
,因为新的ActionBarActivity
禁用并替换了系统操作栏。
回答by Ivo Stoyanov
If your activity is AppCompatActivity, you can get the action bar like this:
如果你的activity是AppCompatActivity,你可以得到这样的操作栏:
android.support.v7.app.ActionBar mActionBar = getSupportActionBar();
回答by kamilws
Object actionBar = getSupportActionBar();
android.support.v7.internal.app.WindowDecorActionBar bar = (android.support.v7.internal.app.WindowDecorActionBar) actionBar;
If you are developing app targeting 21SDK but app is going to be used under older sdk's then this lines above are the solution.
如果您正在开发针对 21SDK 的应用程序,但应用程序将在较旧的 sdk 下使用,那么上面的这一行就是解决方案。
You can't use getActionBar() under 21SDK when your activity extends ActionBarActivity
你的activity扩展ActionBarActivity时不能在21SDK下使用getActionBar()
回答by Imran Khan
Replace ActionBar by android.support.v7.app.ActionBar in all you code. and use setSupportActionBar() also Extent your activity from AppCompatActivity. use android support v7 dependency.
在所有代码中将 ActionBar 替换为 android.support.v7.app.ActionBar 。并使用 setSupportActionBar() 也可以从 AppCompatActivity 扩展您的活动。使用 android 支持 v7 依赖项。