溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android ActionBar返回null的問題

發(fā)布時(shí)間:2020-07-04 02:01:03 來源:網(wǎng)絡(luò) 閱讀:585 作者:無心小書童 欄目:移動(dòng)開發(fā)

學(xué)習(xí)Android4.0的ActionBar,遇到一個(gè)特別惡心的問題,必須記下來。


我開始新建的2.2的工程,后來想測(cè)試ActionBar,看到文檔說是11以后才能用,我就直接把項(xiàng)目改成了min:14,target:17。這也是隱患的開始。


在程序里面調(diào)用下面這句獲取actionBar,但是返回的總是null的,不知道為啥?測(cè)試了一下午,尼瑪啊。。。
ActionBar mActionbar = getActionBar();


我新建了一個(gè)項(xiàng)目,直接新建SDK 14的項(xiàng)目,就可以,返回的就不是null。我特別的納悶,對(duì)比了好久,還是沒發(fā)現(xiàn)問題在哪。其實(shí)聰明的程序員早就應(yīng)該想到,肯定是Theme的問題,我確實(shí)當(dāng)時(shí)沒想到。


晚上吃晚飯,回來問同事才知道,原來是我的Theme設(shè)置的部隊(duì),由于我項(xiàng)目之前是2.2的,theme設(shè)置的是:
<style name="AppBaseTheme" parent="android:Theme.Light">
問題就出在這里了。


那為啥我新建項(xiàng)目就可以呢?我忽略了一點(diǎn):我新的項(xiàng)目的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的設(shè)備上,會(huì)使用第二處,SDK 14會(huì)使用第三處,所以是正常的。而我最初的項(xiàng)目是從2.2改過來的,并沒有values-v11 values-v14這2個(gè)文件,所以不行。


百度了一下,看網(wǎng)上也有同樣的朋友遇到同樣的問題,我估計(jì)都和我的問題是一樣的。還有個(gè)朋友說這是個(gè)bug,其實(shí)不是,是沒有找到最根本的原因。下面的這個(gè)朋友好歹寫了寫自己的測(cè)試體會(huì),也算是對(duì)我有點(diǎn)幫助把。
http://www.cnblogs.com/shortboy/archive/2013/04/18/3029029.html
這個(gè)朋友提到了加下面的就可以出來,但是背景是黑色的,我試過了,確實(shí)如他所述。
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI