自定义ProgressBar

时间:2014-01-10 18:48:30

标签: android android-widget android-drawable android-progressbar

我正在尝试创建一个如下所示的ProgresBar

Desired ProgressBar

到目前为止,我已经创建了一个扩展ProgressBar的对象,现在我想弄清楚我的下一步是什么。

我知道我需要用一些逻辑来覆盖onDraw(),这些逻辑将决定要着色的方块数。这很简单。

我不知道怎么做才是首先获得这些方块。如何替换默认的drawable,所以当我在布局中添加自定义栏时,我可以看到像我的图像?

1 个答案:

答案 0 :(得分:7)

尝试这个自定义Drawable:

class ProgressDrawable extends Drawable {
    private static final int NUM_RECTS = 10;
    Paint mPaint = new Paint();

    @Override
    protected boolean onLevelChange(int level) {
        invalidateSelf();
        return true;
    }

    @Override
    public void draw(Canvas canvas) {
        int level = getLevel();
        Rect b = getBounds();
        float width = b.width();
        for (int i = 0; i < NUM_RECTS; i++) {
            float left = width * i / NUM_RECTS;
            float right = left + 0.9f * width / NUM_RECTS;
            mPaint.setColor((i + 1) * 10000 / NUM_RECTS <= level? 0xff888888 : 0xffbbbbbb);
            canvas.drawRect(left, b.top, right, b.bottom, mPaint);
        }
    }

    @Override
    public void setAlpha(int alpha) {
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}

并在onCreate中使用以下内容进行测试:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

final ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
Drawable d = new ProgressDrawable();
pb.setProgressDrawable(d);
pb.setPadding(20, 20, 20, 0);
ll.addView(pb);

OnSeekBarChangeListener l = new OnSeekBarChangeListener() {
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int newProgress = pb.getMax() * progress / seekBar.getMax();
        Log.d(TAG, "onProgressChanged " + newProgress);
        pb.setProgress(newProgress);
    }
};

int[] maxs = {4, 10, 60, 110};
for (int i = 0; i < maxs.length; i++) {
    SeekBar sb = new SeekBar(this);
    sb.setMax(maxs[i]);
    sb.setOnSeekBarChangeListener(l);
    sb.setPadding(20, 20, 20, 0);
    ll.addView(sb);
}

setContentView(ll);