How to easily change the color of a progressBar in Android?
I would l开发者_运维知识库ike to dynamically update the ProgressBar Color, in order to match with the layout of the application that changes in realtime. The idea is to change the color according to the value set. I found some solution but seems heavy to have that running in an animation updating several times per second.
Use ProgressBar's method:
public void setProgressDrawable (Drawable d)
and pass Drawable in different colors, ex. ColorDrawable which has setColor(int color) method.
To change png drawable colors on the fly try: How to change colors of a Drawable in Android?
EDIT:
ProgressBar drawable is LayerDrawable that looks like:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:drawable/screen_progress_frame" />
<item>
<scale scaleWidth="100%" scaleGravity="0x3" drawable="@android:drawable/screen_progress_inner" />
</item>
</layer-list>
It has ScaleDrawable which you want to colorize.
Create your own LayerDrawable similar to the above and extract bar drawable and change color of it.
This is solution which you can use in code (based on the solution of pawelzieba).
ProgressBar progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
progressBar.setProgressDrawable(new LayerDrawable(
new Drawable[] {
new ColorDrawable(Color.RED),
new ScaleDrawable(new ColorDrawable(Color.GREEN), Gravity.LEFT, 1, -1),
}));
...
progressBar.setProgress(20);
Well, for anyone looking for how to do it programmatically: do not forget to set ids to your Drawables!
Drawable bckgrndDr = new ColorDrawable(Color.RED);
Drawable secProgressDr = new ColorDrawable(Color.GRAY);
Drawable progressDr = new ScaleDrawable(new ColorDrawable(Color.BLUE), Gravity.LEFT, 1, -1);
LayerDrawable resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, secProgressDr, progressDr });
//setting ids is important
resultDr.setId(0, android.R.id.background);
resultDr.setId(1, android.R.id.secondaryProgress);
resultDr.setId(2, android.R.id.progress);
Setting ids to drawables is crucial, and takes care of preserving bounds and actual state of progress bar.
(It seeems that solution proposed by vmayatskii sort of works - but only if you call setProgress(value) aftrawards, and this value has to be different from current progress value)
精彩评论