今天學習Android4.0的ActionBar,遇到一個特別噁心的問題,必須記下來。
我開始建立的2.2的工程,後來想測試ActionBar,看到文檔說是11以後才能用,我就直接把項目改成了min:14,target:17。這也是隱患的開始。
在程式裡面調用下面這句擷取actionBar,但是返回的總是null的,不知道為啥?測試了一下午,尼瑪啊。。。
ActionBar mActionbar = getActionBar();
我建立了一個項目,直接建立SDK 14的項目,就可以,返回的就不是null。我特別的納悶,對比了好久,還是沒發現問題在哪。其實聰明的程式員早就應該想到,肯定是Theme的問題,我確實當時沒想到。
晚上吃晚飯,回來問同事才知道,原來是我的Theme設定的部隊,由於我項目之前是2.2的,theme設定的是:
<style name="AppBaseTheme" parent="android:Theme.Light">
問題就出在這裡了。
那為啥我建立項目就可以呢?我忽略了一點:我新的項目的theme有3處:
1)values --> styles.xml
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
2)values-v11 --> styles.xml
<!--
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>
3)values-v14 --> styles.xml
<!--
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
看懂了吧。就是說:在SDK 11的裝置上,會使用第二處,SDK 14會使用第三處,所以是正常的。而我最初的項目是從2.2改過來的,並沒有values-v11 values-v14這2個檔案,所以不行。
百度了一下,看網上也有同樣的朋友遇到同樣的問題,我估計都和我的問題是一樣的。還有個朋友說這是個bug,其實不是,是沒有找到最根本的原因。下面的這個朋友好歹寫了寫自己的測試體會,也算是對我有點協助把。
http://www.cnblogs.com/shortboy/archive/2013/04/18/3029029.html
這個朋友提到了加下面的就可以出來,但是背景是黑色的,我試過了,確實如他所述。
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);