ActionBar object is returned as null

2019-09-20 16:42发布

问题:

I get actionBar object below as null, and hence a NullPointerException when executing actionBar.setDisplayHomeAsUpEnabled(true). Following is my code which is called from onResume of the Fragment.

ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

Followwing is the theme I apply to the activity in the onCreate:

 <style name="MyActionBarTheme" parent="Theme.AppCompat.Light">

        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="actionMenuTextColor">@color/green</item>
        <item name="colorPrimary">@color/green</item>
        <item name="colorPrimaryDark">@color/greenD</item>

    </style>

My application has minimum api level set to 14. Please help me, explain why is the ActionBar object returned as null.

EDIT: getActivity().getActionBar(); returns null in Fragment.

回答1:

You need to use getSupportActionBar() when you use AppCompatActivity instead of getActionBar().

EDIT

When you use AppCompat theme you have to use AppCompatActivity.

Example code how to get ActionBar:

Activity activity = getActivity();
if(activity != null && activity instanceof AppCompatActivity) {
   AppCompatAcitivyt appCompatActivity = (AppCompatActivity) activity;
   ActionBar actionBar = appCompatActivity.getSupportActionBar();
   //your code
}


回答2:

If you are using appCompat you need to use getSupportActionBar() instead of getActionBar()