androidkotlinalphacolordrawable

Setting alpha of ColorDrawable does not work


I am trying to achieve an effect in my app of where the user scrolls down, the opacity of a view will change from 0 to 1.

To achieve this, I've created a ColorDrawable with my desired color, blue, and then set its alpha to 0.

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

However, after increasing the alpha, it does not change. I've tried printing the value of actionBarBackground but its still 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

Any ideas why the alpha of the ColorDwarable does not change? Thank you.


Solution

  • Thanks to @Jon Goodwin's comment, I finally fixed the problem.

    For some reason, changing the alpha value on a ColorDrawable in Kotlin, does not seem to have any effect (it used to work in Java).

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

    My final, working code from my question:

    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.: Also check his detailed answer on why this happens in Kotlin.