设置ColorDrawable的alpha不起作用

问题描述 投票:1回答:2

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

android kotlin alpha colordrawable
2个回答
1
投票

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

出于某种原因,更改Kotlin中的ColorDrawable上的alpha值似乎没有任何影响(它曾用于Java)。

然而,用你在ColorDrawable上调用Drawable得到的.mutate()替换这个ColorDrawable,使得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.

1
投票

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

但是,用ColorDrawable替换这个Drawable,你可以在ColorDrawable上调用.mutate(),这样可以使alpha更改起作用。

但这不是出于某种原因,有一个原因:

在API级别3中添加了mutate()

open fun mutate():Drawable

可变的BitmapDrawable仍然与来自同一资源的任何其他Drawable共享其Bitmap。

mutate()
Added in API level 3

public Drawable mutate ()

使这个drawable可变。此操作无法逆转。一个可变的drawable保证不与任何其他drawable共享其状态。当您需要修改从资源加载的drawable的属性时,这尤其有用。默认情况下,从同一资源加载的所有drawables实例共享一个公共状态;如果修改一个实例的状态,则所有其他实例将收到相同的修改。在可变的Drawable上调用此方法将不起作用。

reference mutate

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

不可变类是一个类,其状态在创建后无法更改。 Mutability

© www.soinside.com 2019 - 2024. All rights reserved.