设置 ColorDrawable 的 alpha 不起作用

Setting alpha of ColorDrawable does not work

我试图在我的应用程序中实现用户向下滚动的效果,视图的不透明度将从 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 没有改变吗?谢谢。

感谢@Jon Goodwin 的评论,我终于解决了这个问题。

出于某种原因,在 Kotlin 中更改 ColorDrawable 的 alpha 值似乎没有任何效果(它曾经在 Java 中有效)。

但是,将此 ColorDrawable 替换为您在 ColorDrawable 上调用 .mutate() 得到的 Drawable 会使 alpha 更改生效。

我的问题的最终工作代码:

val actionBarBackground = ColorDrawable(ContextCompat.getColor(it, R.color.myBlue)).mutate()
// Keep in mind that actionBarBackground now is a Drawable, not a ColorDrawable
(activity as? AppCompatActivity)?.supportActionBar?.setBackgroundDrawable(actionBarBackground)

actionBarBackground.alpha = 255
Log.d(TAG, "Alpha: ${actionBarBackground.alpha}") // Prints: Alpha: 255
// This also works when called form inside a ScrolView Listener, to fade the actionbar background.

P.S.: 还要查看他关于为什么在 Kotlin 中会发生这种情况的详细回答。

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

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

但是不是原因,有a原因:

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