public class MyProgressBar extends ProgressBar { String text; //文件大小 String percent; //百分比 Paint mPaint; Paint mPaintPercent; //新建Paint在完成时隐藏进度百分比 public MyProgressBar(Context context) { super(context); initText(); } public MyProgressBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initText(); } public MyProgressBar(Context context, AttributeSet attrs) { super(context, attrs); initText(); } @Override public synchronized void setProgress(int progress) { setText(progress); super.setProgress(progress); } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); Rect rect = new Rect(); this.mPaint.getTextBounds(this.text, 0, this.text.length(), rect); int x = (getWidth()) - (rect.centerX() * 2 +10); int y = (getHeight() / 2) - rect.centerY(); canvas.drawText(this.text, x, y, this.mPaint); this.mPaintPercent.getTextBounds(this.percent, 0, this.percent.length(), rect); int x2 = (getWidth() / 2) - rect.centerX(); int y2 = (getHeight() / 2) - rect.centerY(); canvas.drawText(this.percent, x2, y2, this.mPaintPercent); } private void initText() { this.mPaint = new Paint(); this.mPaint.setStrokeWidth(10f); this.mPaint.setTextSize(DisplayUtil.sp2px(getContext(), 13));//setTextSize参数是px this.mPaint.setColor(Color.WHITE); this.mPaintPercent = new Paint(); this.mPaintPercent.setStrokeWidth(10f); this.mPaintPercent.setTextSize(DisplayUtil.sp2px(getContext(), 13));//setTextSize参数是px this.mPaintPercent.setColor(Color.WHITE); } public void setText(int progress) { // int i = (progress * 100) / this.getMax(); // this.text = String.valueOf(i) + "%"; String current = null; String total = null; DecimalFormat df = null; if (this.getMax() < 1024 * 100) { df = new DecimalFormat("##########0.0"); current = df.format((double) progress / 1024); total = df.format((double) this.getMax() / 1024); this.text = current + "K/" + total + "K"; if (total.equals("0.0")){ this.percent = "0.00%"; }else { this.percent = df.format( ((double) progress / 1024) / ((double) this.getMax() / 1024) * 100 ) + "%"; } } else { df = new DecimalFormat("##########0.00"); current = df.format((double) progress / 1024 / 1024); total = df.format((double) this.getMax() / 1024 / 1024); this.text = current + "M/" + total + "M"; if (total.equals("0.00")){ this.percent = "0.00%"; }else { this.percent = df.format(((double) progress / 1024 / 1024) / ((double) this.getMax() / 1024 / 1024) * 100) + "%"; } } } public void setText(String progress) { this.percent = progress; } public void setPercentGone(){ mPaint.setColor(Color.TRANSPARENT); } }
可以显示百分比和文件大小的Progressbar
最新推荐文章于 2023-07-14 08:45:56 发布