4

我想創建一個ProgresBar,看起來像下面這樣:自定義進度

Desired ProgressBar

到目前爲止,我已經創建了擴展進度的目標,現在我想找出我的下一個一步是。

我知道我需要用一些邏輯來覆蓋onDraw(),這些邏輯將決定要打印多少個正方形。這很簡單。

我不知道該怎麼做是讓這些廣場擺在首位。如何替換默認的drawable,所以當我在佈局中添加自定義欄時,可以看到類似於圖像的東西?

+0

所有你需要的是創建一個自定義進度可繪製上水平的變化作出反應,看到繪製對象。 onLevelChange – pskink

+0

@pskink你是說我不需要使用進度條? – BloonsTowerDefence

+0

是的,只是擴展可繪製和使用setProgressDrawable – pskink

回答

7

試試這個自定義繪製對象:

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);