Search code examples
androidandroid-layoutandroid-actionbarandroid-stylesandroid-actionbar-compat

Setting ColorPrimary (Action Bar color) to transparent causes an exception


I'm trying to set my Action Bar color to transparent, so it will have the same color as the background and will also blend in with the gradient background.

I tried doing something like this:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

When I run my app, it launches, loads the screen for one second (all rendered correctly, action bar is transparent), then crashes to the following exception:

java.lang.IllegalArgumentException: background can not be translucent: #0

Tracing to no relevant class of my project. If I set the parameter to a solid color, everything works fine. Can you help me with the problem? I couldn't find any solution.

Thanks.


Solution

  • Your app isn't crashing as a result of the ActionBar background being transparent, but as a result of your colorPrimary being transparent, in combination with using the MediaRouter lib.

    MediaRouterThemeHelper.getControllerColor and MediaRouterThemeHelper.getButtonTextColor both make calls to ColorUtils.calculateContrast, which is where your IllegalArgumentException is coming from.

    ColorUtils.calculateContrast needs a fully opaque color in order to correctly calculate contrast, just based on the formula being used and MediaRouterThemeHelper uses colorPrimary to determine how to theme the MediaRouter controller and button text color.

    It looks like you're using a NoActionBar style, so I'm assuming you're using a Toolbar and just setting the background to be your colorPrimary. Instead you could just use @android:color/transparent directly and change your colorPrimary to something opaque.