通常在使用Android的getActionBar()的时候报空指针异常,通常有5种原因。
1、sdk版本太低:
Actionbar的主题在3.0以后才有,使用的时候要确保最低的版本不能小于3.0。
代码:
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
2、style文件中,添加的主题:
主题要具有ActionBar,例如:
<style name="AppTheme" parent="@android:style/Theme.Holo.Light">
<android:theme=“@style/AppTheme">
3、要做操作的类及其父类中,不要设置为全屏:
代码:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4、 getActionBar()要写在setContentView()后面
5、没有引用到v11+包中的主题
values-v11中代码:
<resources>
<!--
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
<!-- API 11 theme customizations can go here. -->
</style>
</resources>
解决方法:
如果没有values-v11或者v14的包,就去其他工程中copy一份过来,改成上述代码就可以了。