I had a similar problem. I tried to use the layer-list approach that Blueberry suggested, but once I put in a high-res asset for the logo the solution no longer worked. A bitmap in a layer-list has a bug: It will enlarge smaller images to fit the space but won't shrink larger images. So, as long as you are okay with using tiny images that look grainy/pixelated when they are enlarged, layer-list works fine.
To solve this problem and to have a centered high-res logo, I completely removed the android:background
attribute from Toolbar, added android:background="?attr/colorPrimary"
to my AppBarLayout
parent and then tossed this terrible code into my Activity's onCreate
method:
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (ab != null && toolbar != null)
{
// Hide the title text.
ab.setDisplayShowTitleEnabled(false);
// Convert and show the logo.
toolbar.addOnLayoutChangeListener(new View.OnLayoutChangeListener()
{
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)
{
ActionBar ab = getSupportActionBar();
if (ab != null)
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
Bitmap bmp2 = Bitmap.createBitmap(toolbar.getWidth(), toolbar.getHeight(), bmp.getConfig());
Bitmap bmp3 = Bitmap.createScaledBitmap(bmp, bmp.getWidth() * toolbar.getHeight() / bmp.getHeight(), toolbar.getHeight(), true);
Canvas canvas = new Canvas(bmp2);
canvas.drawBitmap(bmp3, (toolbar.getWidth() / 2) - (bmp3.getWidth() / 2), 0, null);
BitmapDrawable background = new BitmapDrawable(getResources(), bmp2);
ab.setBackgroundDrawable(background);
}
}
});
}
It works by creating a canvas the size of the toolbar and a ratio-scaled version of the logo, drawing the newly resized logo onto the canvas in the center, and finally setting the bitmap being drawn on as the background of the action bar.
On the plus side, this approach gives you total control over placement, sizing, etc. Not limited to whatever you can do in XML. It's terrible because it is called pretty regularly whenever the toolbar layout changes, which means there are performance implications. But, when you are required by your design team (that cares not about the first thing regarding Material Design) to have a background logo and waste five hours looking for the solution above, performance stops mattering - you just want the damn thing to work. The above code reeks pretty badly of desperation.
I'll let someone more capable than me in Android development point out that "I'm doing it wrong" and fix whatever performance issues/bugs there are with the above code. It doesn't change the fact that layer-list bitmap is broken and this is a hack (that should not exist) to fix a stupid bug (that should also not exist) in Android.