android - 设置 ColorDrawable 的 alpha 不起作用

标签 android kotlin alpha colordrawable

我试图在我的应用程序中实现用户向下滚动时, View 的不透明度将从 0 更改为 1 的效果。

为了实现这一目标,我创建了一个具有所需颜色(蓝色)的 ColorDrawable,然后将其 alpha 设置为 0。

val actionBarBackground = ColorDrawable(ContextCompat.getColor(it, R.color.myBlue))
(activity as? AppCompatActivity)?.supportActionBar?.setBackgroundDrawable(actionBarBackground)

但是,增加alpha后,它并没有改变。我尝试打印 actionBarBackground 的值,但它仍然是 0...

// This is called inside a scrollview callback that calculates an alpha value between 0 and 255
actionBarBackground.alpha = 255
Log.d(TAG, "Alpha: ${actionBarBackground.alpha}") // Prints: Alpha: 0

有什么想法为什么 ColorDwarable 的 alpha 没有改变吗?谢谢。

最佳答案

我想我应该回答,正如 Lucas P. 所说:

However, replacing this ColorDrawable with the Drawable you get from calling .mutate() on the ColorDrawable, makes the alpha changes work.

但由于某些原因,,有原因:

mutate() added in API level 3

open fun mutate(): Drawable

A mutable BitmapDrawable still shares its Bitmap with any other Drawable that comes from the same resource.

mutate()
Added in API level 3

public Drawable mutate ()

Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

reference mutate

Kotlin 自动区分可变和不可变集合——cool(如果你知道这意味着什么)。

An immutable class is a class whose state cannot be changed once it has been created.
Mutability

关于android - 设置 ColorDrawable 的 alpha 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55283913/

相关文章:

java - 在 AVD 上安装应用程序时出现 Logcat 警告

uml - 生成 Kotlin 类图

kotlin - 如何在 kotlin 中使用 Snackbar.make(view, Str_Msg, Snackbar.LENGTH_SHORT)

Android Websocket 错误

android - 为什么PackageManager.queryIntentActivities方法只返回ACTION_VIEW的默认浏览器信息?

java - 如何混合 alpha 值?

objective-c - 将 View 的 Alpha 设置为从 0 到 0.5 的动画

css - 如何使 WebGL Canvas 透明

android - 如何避免多个兼容性项目 appcompat_v7

kotlin - 为什么::语法在某些情况下无法调用kotlin函数?