Android toolbar setNavigationIcon not working
Asked Answered
S

3

11

So, I have a BaseActivity in which I have a toolbar and I call setSupportActionBar(toolbar).

In some of my activities that extends BaseActivity, I would like to change the navigation icon (the default arrow) to another drawable. But when I call toolbar.setNavigationIcon(myDrawable) it doesn't work, it still shows the default left pointing arrow icon.

Any idea? Thanks.

Stet answered 29/10, 2014 at 21:48 Comment(1)
possible duplicate : #26525729Nightfall
V
49

I think you can set like this

    menuDrawerToggle = new ActionBarDrawerToggle(this, menuDrawer, toolbar, R.string.drawer_open, R.string.drawer_close){...}

    menuDrawerToggle.syncState();

    toolbar.setNavigationIcon(getResources().getDrawable(yourDrawable));

put setNavigationIcon after syncState()

Vanzandt answered 14/1, 2015 at 6:20 Comment(5)
WTF!?!? I would never have found this, how the heck did you figure this out? I'd throw you a bunch of rep if I knew how.Sting
How does this only have (now 7) votes. Great find!!Comedy
Great answer. Can't belive itGorgonian
This is the right answer. Works like a charm! Life saver!Deathday
What logic does this use? I’ve tried android:navigationIcon="@drawable/ic_navigation” in my android.support.v7.widget.Toolbar design file and it failed. Tried toolbar.setIcon in onCreate after setSupportActionBar(toolbar); and it failed but this works. Is there anything in the documentation that mentions that navigationIcon must be set after a call to syncState. What is the issue here / what goes on under the hood?Charmian
A
5

In my case: I don`t use ActionBarDrawerToggle. For me helpful was: to change order of methods calls.

From:

Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_chevron_left_white_24dp);

To:

Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_chevron_left_white_24dp);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
Allstar answered 16/5, 2017 at 10:54 Comment(0)
L
5

In my case, setNavigationIcon after syncState as @Hsieh not work! My solution is set in onPostCreate method as below. Override this method in your activity

  @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mToolbar.setNavigationIcon(R.drawable.ic_menu_button);
    }
Label answered 7/11, 2017 at 9:19 Comment(1)
oh, there're too many cases for this issue. :'( Share your solutions if you find out, bro!Pharmacist

© 2022 - 2024 — McMap. All rights reserved.