Custom ProgressBar

前端 未结 1 521
天涯浪人
天涯浪人 2020-11-29 09:16

I am trying to create a ProgresBar that looks like the following:

\"Desired

相关标签:
1条回答
  • 2020-11-29 09:25

    try this custom 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;
        }
    }
    

    and test it with the following in 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);
    
    0 讨论(0)
提交回复
热议问题