Progress bar with divider

后端 未结 3 660
清歌不尽
清歌不尽 2020-11-27 17:58

Can someone please explain to me how to implement a progress bar with a divider just like its shown on the image below?

3条回答
  •  广开言路
    2020-11-27 18:11

    replace ProgressDrawable from my answer with the modified one:

    class ProgressDrawable extends Drawable {
        private static final int NUM_SEGMENTS = 4;
        private final int mForeground;
        private final int mBackground;
        private final Paint mPaint = new Paint();
        private final RectF mSegment = new RectF();
    
        public ProgressDrawable(int fgColor, int bgColor) {
            mForeground = fgColor;
            mBackground = bgColor;
        }
    
        @Override
        protected boolean onLevelChange(int level) {
            invalidateSelf();
            return true;
        }
    
        @Override
        public void draw(Canvas canvas) {
            float level = getLevel() / 10000f;
            Rect b = getBounds();
            float gapWidth = b.height() / 2f;
            float segmentWidth = (b.width() - (NUM_SEGMENTS - 1) * gapWidth) / NUM_SEGMENTS;
            mSegment.set(0, 0, segmentWidth, b.height());
            mPaint.setColor(mForeground);
    
            for (int i = 0; i < NUM_SEGMENTS; i++) {
                float loLevel = i / (float) NUM_SEGMENTS;
                float hiLevel = (i + 1) / (float) NUM_SEGMENTS;
                if (loLevel <= level && level <= hiLevel) {
                    float middle = mSegment.left + NUM_SEGMENTS * segmentWidth * (level - loLevel);
                    canvas.drawRect(mSegment.left, mSegment.top, middle, mSegment.bottom, mPaint);
                    mPaint.setColor(mBackground);
                    canvas.drawRect(middle, mSegment.top, mSegment.right, mSegment.bottom, mPaint);
                } else {
                    canvas.drawRect(mSegment, mPaint);
                }
                mSegment.offset(mSegment.width() + gapWidth, 0);
            }
        }
    
        @Override
        public void setAlpha(int alpha) {
        }
    
        @Override
        public void setColorFilter(ColorFilter cf) {
        }
    
        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }
    }
    

    and create it like this:

    Drawable d = new ProgressDrawable(0xdd00ff00, 0x4400ff00);
    

提交回复
热议问题