getActionBar returns null
It seems you need to request having an Actionbar (!= titlebar) either via a Theme or via below code.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The Action Bar is a window feature. The feature must be requested
// before setting a content view. Normally this is set automatically
// by your Activity's theme in your manifest. The provided system
// theme Theme.WithActionBar enables this for you. Use it as you would
// use Theme.NoTitleBar. You can add an Action Bar to your own themes
// by adding the element <item name="android:windowActionBar">true</item>
// to your style definition.
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.main);
// experiment with the ActionBar
ActionBar actionBar = getActionBar();
actionBar.hide();
}
Code from [here]
It seems there are several conditions which need to be met in order for this to work. The one which stumped me for a long time was this:
Make sure your activity extends Activity (NOT ActionBarActivity).
public class MagicActivity extends Activity
Make sure your app manifest has something like
<application
...
android:theme="@android:style/Theme.Holo" >
and make sure your activity layout has
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
....
android:theme="@android:style/Theme.WithActionBar" >
-Mark
I seemed to solve all my errors by switching getActionBar() with getSupportActionBar(). I had tried different themes, adding getWindow().requestFeature(Window.FEATURE_ACTION_BAR);, made sure the setContentView(view) was first and all the other things seen before.
Action bar needs theme or activity with app title to be there. Make sure you have not styled your application or activity as Theme.NOTITLE.
<application
android:name="com.xxx.yyy.Application"
android:debuggable="false"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/Theme.NoTitle"> // remove this line if you have this in your code
<activity
android:name="com.xxx.yyy.Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/Theme.NoTitle" // remove this line if you have this in your code
android:windowSoftInputMode="adjustResize|stateHidden" >
I was trying to get the ActionBar from within a fragment inside an ActionBarActivity using the support library. I had to do this:
ActionBarActivity actionBarActivity = (ActionBarActivity)getActivity();
ActionBar actionBar = actionBarActivity.getSupportActionBar();
My next quest is to figure out how to make this generic. For example, this code feels dirty because it requires my Fragment to know both that it's being used by an ActionBarActivity and using the support library. I think it should be a method that checks getActivity().getActionBar()
first followed by the code above catching the ClassCastException if the parent Activity is not an ActionBarActivity.