ActionBar returns as null

I get the actionBar object below as null, and therefore, a NullPointerException when I execute actionBar.setDisplayHomeAsUpEnabled(true) . Below is my code that is called from the onResume snippet.

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

Followwing is a theme that I apply to onCreate activity:

  <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 a minimum api level of 14. Please help me, explain why the ActionBar returned as null.

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

-1
source share
2 answers

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

EDIT

When you use the AppCompat theme, you should use AppCompatActivity .

Sample code on how to get an ActionBar :

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

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

+1
source

Source: https://habr.com/ru/post/1235493/


All Articles