11

I have custom seekbar and I can change the the color in the onProgressChanged by setting a new progress drawable:

seek.setProgressDrawable(res.getDrawable(R.drawable.seekbar_bg1));

But I would like a seekbar which has a solid color from green to red depending on the progress. Is there a way to use something like a gradient color so I don't need to create like 100 drawables this?

    <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

 <item android:id="@android:id/background">
  <shape>
    <solid android:color="@android:color/transparent" />
  </shape>
</item>

<item android:id="@+id/progressshape">
<clip>
  <shape>
    <solid android:color="@color/custom_yellow" />
  </shape>
</clip>
</item>

</layer-list>

For those who are interested in the solution. I use the following code:

this method to set the color:

public void setProgressBarColor(int newColor){ 
  LayerDrawable ld = (LayerDrawable) getProgressDrawable();
  ClipDrawable d1 = (ClipDrawable) ld.findDrawableByLayerId(R.id.progressshape);
  d1.setColorFilter(newColor, PorterDuff.Mode.SRC_IN);
}

and in the onProgressChanged:

 if(progress <= 50){
                seek.setProgressBarColor(Color.rgb( 255 - (255/100 * (100 - progress*2)), 255, 0));
 }else{
                seek.setProgressBarColor(Color.rgb( 255, 255 - (255/100 * (progress - 50)*2), 0));
 }
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Luciano
  • 2,691
  • 4
  • 38
  • 64

2 Answers2

28

I do something like this using this method:

public void setProgressBarColor(ProgressBar progressBar, int newColor){ 
    LayerDrawable ld = (LayerDrawable) progressBar.getProgressDrawable();
    ClipDrawable d1 = (ClipDrawable) ld.findDrawableByLayerId(R.id.progressshape);
    d1.setColorFilter(newColor, PorterDuff.Mode.SRC_IN);

}

Then, when you update the progress, you just have to change the desired color.

Alesqui
  • 6,417
  • 5
  • 39
  • 43
  • How can I access the R.id.progressshape that is used by default? – snapfractalpop Apr 09 '12 at 15:30
  • 3
    "android.R.id.progress" via code or "@android:id/progress" via xml (don't know if this was what you asked for though) – Alesqui Apr 09 '12 at 16:01
  • 4
    This worked for me until Android 5.0, where getProgressDrawable() returns a StateListDrawable instead of a Drawable, and throws a ClassCastException. I've reported this as a bug, and included a workaround in the bug report: https://code.google.com/p/android/issues/detail?id=82062 – arlomedia Dec 08 '14 at 20:29
5

Use this :

bar.setProgressDrawable(new ColorDrawable(Color.rgb( red, green, blue)));

Change the red,green,blue with progress change.

asish
  • 4,767
  • 4
  • 29
  • 49
  • thnx for trying to help, but the progress drawable need to like above (a layer-list with a shape and a clip).. Do you know how i can create this drawable programmatically or edit the clip shape color in runtime? – Luciano Mar 23 '12 at 13:12