Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing gradient background colors on Android at runtime

I'm experimenting with Drawable backgrounds and have had no problems so far.

I'm now trying to change the gradient background color at runtime.

Unfortunately, there's no API to change it at runtime, it seems. Not even by trying to mutate() the drawable, as explained here: Drawable mutations

The sample XML looks like this. It works, as expected.

<shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle">     <gradient         android:startColor="#330000FF"         android:endColor="#110000FF"         android:angle="90"/> </shape> 

Sadly, I want a list with various colors, and they'd have to be programatically altered at runtime.

Is there another way to create this gradient background at runtime? Perhaps even not using XML altogether?

like image 410
Phenome Avatar asked Feb 09 '11 05:02

Phenome


People also ask

How do you do a gradient on mobile?

To create a gradient color we need to create a . xml file in the drawable folder. So go to app -> res -> drawable and right-click on drawable -> New -> Drawable Resource File and create gradient_drawable.


1 Answers

Yes! Found a way!

Had to forget about XML, but here's how I did it:

On my getView() overloaded function (ListAdapter) I just had to:

    int h = v.getHeight();     ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());     mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, h, Color.parseColor("#330000FF"), Color.parseColor("#110000FF"), Shader.TileMode.REPEAT));     v.setBackgroundDrawable(mDrawable); 

And that gave me the same result as the XML background above. Now I can programmatically set the background color.

like image 85
Phenome Avatar answered Sep 18 '22 11:09

Phenome