getActionBar() returns Null (AppCompat-v7 21)

寵の児 提交于 2019-12-17 04:06:08

问题


My app is crashing the minute I run it after I changed my AppCompat-v7 to 21.0.0 and Compiled with no problem.

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.


回答1:


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.




回答2:


If your activity is AppCompatActivity, you can get the action bar like this:

android.support.v7.app.ActionBar mActionBar = getSupportActionBar();



回答3:


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.

You can't use getActionBar() under 21SDK when your activity extends ActionBarActivity




回答4:


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.



来源:https://stackoverflow.com/questions/26435231/getactionbar-returns-null-appcompat-v7-21

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!