Android ActionBar返回null的問題

來源:互聯網
上載者:User

今天學習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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.