与ProgressBar一起移动的进度文本

时间:2018-03-07 20:09:21

标签: android android-animation textview android-progressbar

我在Android中有一个水平ProgressBar,可以动画显示当前值。但是,我想更新它,以便它有一个TextView显示进度条的进度,并随着进度的增加随着条的右边缘移动。我想也许我可以创建一个自定义的ProgressBar并以某种方式利用onDraw方法,但我不确定之后的下一步行动是什么。有关更好的方法或某些可能指向正确方向的建议吗?

A basic example of what I'm trying to achieve

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我找到了解决我想要做的事情的方法!灵感来自我在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);
}