我试图在我的应用程序中实现用户向下滚动时, 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 theDrawable
you get from calling .mutate() on theColorDrawable
, 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.
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/