Android get Support Action Bar always returns NULL

爱⌒轻易说出口 提交于 2019-12-08 17:11:34

问题


I'm using the support library v7 on a certain project. I'm trying to instantiate the support action bar like this:

ActionBar actionBar = getSupportActionBar();

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(R.layout.top_action_bar);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setHomeButtonEnabled(true);

Everything works fine on Android devices with API lvl below 11. However, while trying to run the same code on newer devices, like a Samsung Galaxy S4 with Android 4+, getSupportActionBar() always returns null, causing the expected crash. I'm using this style file:

<style name="my_style" parent="@style/Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/my_style_ab</item>
    <item name="android:windowNoTitle">true</item>

</style>

<style name="my_style_ab" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:height">70dp</item>
</style>

Any hints on what may be wrong? I think it has something to do with the style, or maybe I just can't use the support ActionBar on API lvl above 11. Thanks in advance.


回答1:


Using android:windowNoTitle with true is hiding your ActionBar




回答2:


I got the solution. And I didn't provide enough information in the question so it may be hard for others to help. However, I don't know why the problem happens, I just found out how to solve it. The error was due to the app title. I removed this item from the style:

        <item name="android:windowNoTitle">true</item>

And also all the references in the code regarding that title bar, like this one:

  requestWindowFeature(Window.FEATURE_NO_TITLE);

Why does this solve it? still don't know. It may be useful for me if someone can explain it.




回答3:


If you are using Toolbar and AppCompat then you probably have android:windowNoTitle set to true, hiding your action bar. Create a Toolbar in your xml and add this code in the onCreate() of your activity.

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);



回答4:


Inside Manifest file, check the activity for which are you having the issue. I have the theme with "NoActionBar" Property.

Removing it resolved this code worked for me.

android:theme="@style/AppTheme.NoActionBar"



来源:https://stackoverflow.com/questions/21536018/android-get-support-action-bar-always-returns-null

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