Kevin Murvie
Kevin Murvie

Reputation: 2652

Android - getActionBar() null reference

I'm following this Androidhive tutorial for sliding menu using DrawerLayout

I've tried using their code to make a new project and it works, BUT! When I tried applying it into my actual class, it doesn't work......... It returns null value. I used it like..

ActionBar actionBar = getActionBar();
...
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeButtonEnabled(true);

I used the theme :

<style name="AppThemeWithAction" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorControlNormal">@color/textColor</item>
        <item name="colorControlActivated">@color/miBlue</item>
    </style>

I've researched that it might be because of I have no TitleBar, but it doesn't seem to be that way..

If I have missed any essential info to solve the problem, please do comment

UPDATE :

I am trying not to modify the source like changing the ActionBar into Toolbar because I might ruin something else in process lol.

So.. My question now is.. Is every method on ActionBar can be used for Toolbar? Is there any equivalent for the former bar to the latter bar??

For example :

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ){
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

Will changing into Toolbar cause compatibility issues to Kitkat and below though?

Upvotes: 0

Views: 162

Answers (2)

Jackson Chengalai
Jackson Chengalai

Reputation: 3937

If you are using AppCompat you always have to call getSupportActionBar() no matter which Android Version your App is running.

ActionBar actionBar =getSupportActionBar();

I would advise you to use the new Toolbar instead of ActionBar, because it's way more flexible to use.

Upvotes: 2

Pankaj
Pankaj

Reputation: 8058

You Have to extend your Activity as

public yourActivityName extends AppCompatActivity

And then use

  ActionBar actionBar = getSupportActionBar();

Import ActionBar as support v7

Upvotes: 0

Related Questions