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
ActionBar.setHomeAsUpIndicator(...);
This one works for me.
In case you want to change menu icon. (maybe somebody will need it)
In your activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_info, menu);
return true;
}
in your menu folder in res. (menu_info.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_info_action"
android:icon="@drawable/ic_info_icon"
android:title="@string/information"
app:showAsAction="ifRoom"/>
</menu>
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.
The current most efficient way to achieve this:
first display the left hand side icon correctly, call this function in onCreateView or onCreate:
protected void enableDisplayHomeAsHome(boolean active) {
ActionBar actionBar = 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:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: { //index returned when home button pressed
homeButtonPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}