Member-only story

Programmatically Change Drawable Gradient in Android Studio

Code on the Rocks
3 min readJan 30, 2020

--

In Android, a drawable is simply a graphic that can be drawn to the screen of your application. Rather than blow up the size of your app by tossing loads of PNGs into your resource folder, you can provide the device with a set of instructions on how to render the screen. In this article, I will show you how to programmatically manipulate a drawable gradient.

Set Up the Drawable

In this example, we’ll be changing the gradient used to shade in the background of a CardView. Inside the drawable folder of my resources, I created an XML file for my base drawable that looks like this:

My card_corner dimension is set to 4dp (this is can be confiigured by adding a line to your “dimens” subfolder in your values folder). These settings create a basic rectangular card shape with rounded corners for maximum viewing pleasure.

Dynamically Change the CardView Background

The code below should be pasted into the onBindViewHolder function of your RecyclerView adapter.

--

--

No responses yet