我找到了一个解决我所要做的事情的方法!受我在上找到的代码启发
this post.
它将适用于ProgressBar的主要进度和次要进度。我首先扩展了ProgressBar类,并添加了所有构造函数方法。然后,我重写了onDraw方法,如下所示:
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Create the paint for the text
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(getHeight()/4);
Rect bounds = new Rect();
textPaint.getTextBounds(textPrimary, 0, textPrimary.length(), bounds);
//mTypeface is a typeface that I have being set in another function so
//you don't have to use the default! :D
if(mTypeface != null) {
textPaint.setTypeface(mTypeface);
}
//I believe this is done to be able to put values in dp
float density = getContext().getResources().getDisplayMetrics().density;
//Point to draw text for primary progress
float percentage = getProgress() / 100f; //get the total progress
// distance the text should be from the end of the progress in dp
// (paddingPrimary) is number of dp
float x = getWidth() * percentage - (paddingPrimary * density);
// center the text vertically
float y = getHeight() / 2 - bounds.centerY();
//Point to draw text for secondary progress
float percentageSecondary = getSecondaryProgress() / 100f;
float x2 = getWidth() * percentageSecondary - (paddingSecondary * density);
float y2 = getHeight() / 2 - bounds.centerY();
//Draw the numbers to the canvas
//(textPrimary and textSecondary are the text to be drawn)
canvas.drawText(textPrimary, x, y, textPaint);
canvas.drawText(textSecondary, x2, y2, textPaint);
}