与 ProgressBar 一起移动的进度文本

Progress text that moves along with ProgressBar

我在 Android 中有一个水平 ProgressBar,它根据当前值设置动画。但是,我想对其进行更新,使其具有一个显示进度条进度的 TextView,并随着进度的增加与进度条的右边缘一起移动。我想也许我可以创建一个自定义 ProgressBar 并以某种方式利用 onDraw 方法,但我不确定在那之后的下一步是什么。关于更好的方法或可以为我指明正确方向的东西的任何建议?

A basic example of what I'm trying to achieve

非常感谢任何帮助。

我找到了解决方案!受我在 this post. 上找到的代码的启发,它适用于 ProgressBar 的主要和次要进度。我首先做的是扩展 ProgressBar class,并添加所有构造方法。然后我重写了 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);
}