Search code examples
javaandroidandroid-actionbarnavigation-drawer

How to make Navigation drawer toggle button visible on Toolbar?


I am getting error message : ActionBarDrawerToggle: DrawerToggle may not show up because NavigationIcon is not visible. You may need to call actionbar.setDisplayHomeAsUpEnabled(true);

But I have called this in my code , still getting same error and the toggle button is not visible.

My code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //layout variables
    mDrawerLayout = findViewById(R.id.main_drawer_layout);
    mNavigationView = findViewById(R.id.main_nav_view);


    mActionDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mActionDrawerToggle);
    mActionDrawerToggle.syncState();

    //changed as keeps throws NULLPOINTEXCEPTION
    if(getSupportActionBar() != null) {
       // getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        // assigning ID of the toolbar to a variable
         toolbar = (Toolbar) findViewById(R.id.my_toolbar);

        // using toolbar as ActionBar
        setSupportActionBar(toolbar); //set


        ActionBar actionbar = getSupportActionBar(); //get
        actionbar.setTitle("SharePixel");
        actionbar.setDisplayHomeAsUpEnabled(true);
        actionbar.setHomeAsUpIndicator(R.drawable.ic_home_menu);


    }

Solution

  • setHomeAsUpIndicator() won't get executed as the if(getSupportActionBar() != null) condition shouldn't be valid in drawer-based activity, because it requires a custom Toolbar, and you call this condition before setting the custom toolBar.

    This condition won't be achieved unless your activity theme has an ActionBar set in your styles/themes XML. (if you've no customized activity theme set, then it's inherited from the base application theme.

    To fix this:

    1. Make sure that your activity theme inherits from a NoActionBar decedent; for instance Theme.MaterialComponents.DayNight.NoActionBar (or if your activity doesn't have customized style; do that on the base application theme).
    2. Remove the if(getSupportActionBar() != null) condition.