将 ColorPrimary(Action Bar 颜色)设置为透明导致异常

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

我正在尝试将我的 Action Bar 颜色设置为透明,这样它的颜色就会与背景颜色相同,并且还会与渐变背景融为一体。

我试过这样做:

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

当我 运行 我的应用程序启动时,加载屏幕一秒钟(全部正确呈现,操作栏是透明的),然后崩溃并出现以下异常:

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

追踪到与我的项目无关的class。 如果我将参数设置为纯色,一切正常。 你能帮我解决这个问题吗?我找不到任何解决方案。

谢谢。

您的应用程序不会因 ActionBar 背景透明而崩溃,而是由于您的 colorPrimary 透明并结合使用 MediaRouter 库.

MediaRouterThemeHelper.getControllerColor and MediaRouterThemeHelper.getButtonTextColor both make calls to ColorUtils.calculateContrast,这是您的 IllegalArgumentException 的来源。

ColorUtils.calculateContrast 需要完全不透明的颜色才能正确计算对比度,只是基于 formula being usedMediaRouterThemeHelper 使用 colorPrimary 来确定如何主题 MediaRouter 控制器和按钮文本颜色。

看起来您使用的是 NoActionBar 样式,所以我假设您使用的是 Toolbar 并将 background 设置为您的 colorPrimary.相反,您可以直接使用 @android:color/transparent 并将 colorPrimary 更改为不透明的内容。