Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

//...Toolbartoolbar= (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.

Solution 2:

In case you want to change menu icon. (maybe somebody will need it)

  1. In your activity

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
        MenuInflaterinflater= getMenuInflater();
        inflater.inflate(R.menu.menu_info, menu);
        returntrue;
    }
    
  2. in your menu folder in res. (menu_info.xml)

    <?xml version="1.0" encoding="utf-8"?><menuxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"><itemandroid:id="@+id/menu_info_action"android:icon="@drawable/ic_info_icon"android:title="@string/information"app:showAsAction="ifRoom"/></menu>

Solution 3:

The current most efficient way to achieve this:

first display the left hand side icon correctly, call this function in onCreateView or onCreate:

protectedvoidenableDisplayHomeAsHome(boolean active) {
    ActionBaractionBar= getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(active); // switch on the left hand icon
        actionBar.setHomeAsUpIndicator(R.drawable.ic_action_home); // replace with your custom icon
    }
}

Now you can intercept this button press in your activity:

@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {  //index returned when home button pressedhomeButtonPressed();
            returntrue;
        }
    }
    returnsuper.onOptionsItemSelected(item);
}

Solution 4:

ActionBar.setHomeAsUpIndicator(...);

This one works for me.

Post a Comment for "Custom Icon In Android Toolbar"