Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActionBar returns null

Calling getActionBar returns null. This has been frequently reported so I've made sure to include the solutions others have used: My minSdkVersion=11, I do have a titlebar, and I'm calling getActionBar after setContentView. Also, my activity is not a child activity.

setContentView(R.layout.main);

// experiment with the ActionBar 
ActionBar actionBar = getActionBar();
actionBar.hide();

Device is a Samsung Galaxy Tab 10.1 running Android 3.2

Thanks in advance for any ideas or suggestions!

like image 550
user316117 Avatar asked Sep 10 '25 02:09

user316117


2 Answers

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]

like image 164
zapl Avatar answered Sep 12 '25 16:09

zapl


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

like image 34
Mark Smith Avatar answered Sep 12 '25 16:09

Mark Smith