Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

How to override ProgressBar in order to change the progress fill to a drawable with rounded corners and color

I have a specific color that I create programmatically.

I use that color in a GradientDrawable.

I need to override some part of the ProgressBar source code in order to make it use that GradientDrawable in there, when creating the progress fill color, but I dont know which part should I override and where to put my code

This is the progressbar source code:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/widget/ProgressBar.java

This is the drawable I want to use, but it doesnt extend accordingly to the progress made

public static GradientDrawable progressBarProgressDrawable(Context context, float[] radii) {
    GradientDrawable shape = new GradientDrawable();
    shape.setCornerRadii(radii);
    shape.setColor(context.getResources().getColor(R.color.green_button));

    float brightness = 0.9f;
    float[] hsb = new float[] { 43, 23, (33 * brightness) };
    int alpha = 77;
    int newColor = Color.HSVToColor(alpha, hsb);
    shape.setColor(newColor);

    return shape;
}

Upvotes: 3

Views: 523

Answers (2)

pskink
pskink

Reputation: 24720

try this:

    final ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
    setContentView(pb);

    GradientDrawable gd = new GradientDrawable();
    gd.setCornerRadius(32);
    final Drawable cd = new ClipDrawable(gd, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    pb.setProgressDrawable(cd);

    OnTouchListener l = new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int progress = (int) (event.getX() * pb.getMax() / pb.getWidth());
            pb.setProgress(progress);
            float[] hsv = {
                    event.getX() * 360 / pb.getWidth(), 1, 1
            };
            int color = Color.HSVToColor(hsv);
            Log.d(TAG, "onTouch " + Integer.toHexString(color));
            cd.setColorFilter(color, Mode.SRC_ATOP);
            return true;
        }
    };
    pb.setOnTouchListener(l);

Upvotes: 1

Pphoenix
Pphoenix

Reputation: 1473

ProgressBar has a method setBackgroundColor(int color).

If you want to override it, you can

@Override
public void setBackgroundColor (int color) {
    int c = 0x0000ff00; // Using green
    super.setBackgroundColor(c);
}

Or you could just call

ProgressBar bar = new ProgressBar();
bar.setBackgroundColor(c);

Upvotes: 0

Related Questions