Skip to content

Instantly share code, notes, and snippets.

@jtmuller5
Created January 30, 2020 05:15
Show Gist options
  • Save jtmuller5/befcd41ba138e2312ae39083ffba3724 to your computer and use it in GitHub Desktop.
Save jtmuller5/befcd41ba138e2312ae39083ffba3724 to your computer and use it in GitHub Desktop.
Programmatically Changing Drawable Gradient
// Change card gradient based on POS
var background = ResourcesCompat.getDrawable(main.resources, R.drawable.card_gradient, null) as GradientDrawable
var colorList = IntArray(10) {getWhiteColor()} // Create an integer array of all white values
background.mutate() // Mutate the drawable so changes don't affect every other drawable
// background.setGradientCenter(0.1F, 0.5F) // Reset the center of the gradient (default is 0.5F, 0.5F)) - Only works for radial and sweep types
// Conditionaly change the last color in the integer array
when (word?.partOfSpeech) {
"noun" -> colorList[colorList.size-1] = Color.argb(255, 66, 133, 244) // Blue
"verb" -> colorList[colorList.size-1] = Color.argb(255, 15, 157, 88) // Green
"adjective" -> colorList[colorList.size-1] = Color.argb(255, 219, 68, 55) // Red
else -> colorList[colorList.size-1] = Color.argb(255, 244, 180, 0) // Yellow
}
background.setColors(colorList) // Change the drawable's gradient to your new color list
holder.wordCard.background = background // Update the card background to the gradient drawable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment