Search code examples
androidandroid-toolbar

Custom icon in Android toolbar


I'm trying to use define a custom icon in the support Toolbar but the only icon shown is a left arrow... I tried to set it in the layout and programmatically but the result is the same.

Here is my Activity

public class MainActivity extends ActionBarActivity {

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_launcher);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);
}

And my toolbar layout

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:navigationIcon="@drawable/ic_action_bar"
    android:minHeight="@dimen/action_bar_size"
    android:background="?attr/colorPrimary"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    />

Solution

  • Just tried it myself and the issue seems to be that you have to call setNavigationIcon after setSupportActionBar(toolbar). Otherwise it'll only show the arrow as you've described.
    So to fix this issue just change the code like this:

    //...
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_launcher);
    toolbar.setTitle("");
    

    Note: Same goes for setting the title, contentDescription etc. I don't know if this a bug or if it is intended, but it's definitely kinda strange.