9

Is there a way to make the new Android support Toolbar:

android.support.v7.widget.Toolbar

Have a transparent background?

I tried setting the colorPrimary to an ARGB (#00ffffff) but it just gives me a solid gray bar. And Toolbar only allows me to set a background drawable. Is it kosher to set the background drawable to a transparent PNG, or is there a better way to do this?

Ideally I'd be able to do it in code / animate it so certain activities have a transparent bar and some activities don't.

Thanks in advance.

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
Keith
  • 4,144
  • 7
  • 25
  • 43

2 Answers2

20

You can either set the background to android's default transparent color, which works just fine. Add this to the layout you want a transparent Toolbar:

android:background="@android:color/transparent"

If you want to change the alpha programmatically, you can do it by modifying the alpha on the Toolbar background itself. Just get an instance of the Drawable and set the alpha there:

mToolbar = findViewById(R.id.my_toolbar);
mToolbar.getBackground().setAlpha(0);
ebarrenechea
  • 3,775
  • 1
  • 31
  • 37
  • 1
    Thanks a lot for the tip! That worked great. I realized that the default gray I was seeing was actually the background behind the Toolbar. – Keith Oct 27 '14 at 07:31
  • is there anyway to set the toolbar background alpha with a float variable? – Nicholas Pesa Nov 26 '14 at 20:17
  • 1
    @ebarrenechea i have done same for my detail screen. But when i came back to first screen, my toolbar on first screen also become transparent. why is it so.. ? – Shreyash Mahajan May 08 '15 at 13:10
  • @iDroidExplorer do your screens share the same toolbar (i.e. are they fragments in the same activity)? – ebarrenechea May 09 '15 at 01:12
  • @ebarrenechea no they are not fragments. I have opening second activity, where i can set the toolbar background as per your code and then when i came back to my first screen, my first screen's toolbar become transparent. Please help me in this case... – Shreyash Mahajan May 09 '15 at 03:50
  • @iDroidExplorer i am having the same problem. Why does it happen. were you able to figure out ?? – Ramesh Oct 17 '15 at 09:28
  • 2
    @Ramesh I've had the same problem. It looks like this ColorDrawable background of the Toolbar is shared between activities, so when you change the alpha or the color of this ColorDrawable it will also be changed in other Activities. A solution to this problem is setting a new ColorDrawable as background for the Toolbar. – mennovogel Dec 22 '16 at 13:49
9

To answer Nicholas Pesa's question and maybe some others in the future you could set the alpha with a float by using a ratio, something like.

mToolbar.getBackground().setAlpha((int)(myFloatValue) * 255);
Jraco11
  • 4,526
  • 3
  • 20
  • 20