I\'d like to dynamically change the background color of a progress bar in android. I followed the \"bonus\" part near the end of the page of this tutorial:
http://colint
Well, for anyone looking for how to do it programmatically:
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 });
resultDr.setId(0, android.R.id.background);
resultDr.setId(1, android.R.id.secondaryProgress);
resultDr.setId(2, android.R.id.progress);
progressBar.setProgressDrawable(resultDr);
Setting ids to drawables is crucial, and takes care of preserving bounds and actual state of progress bar
See Android ProgressBar.setProgressDrawable only works once? for the answer, repeated below:
What I found out is that the drawable doesn't know it's size when setprogressdrawable is called. When it is initially set up, it does know it's size. This means there is a new drawable set to the seekbar, but the size of the drawable is 0, you won't see anything.
The solution is to first get the bounds of the current drawable, then set the new drawable and finally set the bounds again:
Rect bounds = mySeekBar.getProgressDrawable().getBounds();
mySeekBar.setProgressDrawable(newSeekBarBackground);
mySeekBar.getProgressDrawable().setBounds(bounds);